我想做一些客户端不需要知道的CPU处理。我正在考虑使用https://github.com/audreyt/node-webworker-threads包来做到这一点(例如,将音频文件从ogg转换为raw)。
我想象我可以使用res.send(200)
,然后像这样启动worker:
res.send(200);
var worker = new Worker(function(){
this.onmessage = function(event) {
//do conversion here by calling ffmpeg
};
});
worker.onmessage = function(event) {
//upload file to S3
};
worker.postMessage('filename');
此工作或表达式是否将等待此函数结束后发送回响应?这会阻塞事件线程吗?如果我正在使用webworker - threads,我希望不会。
您可以创建子进程来完成此操作。点击这个链接了解更多细节。要了解这个过程,请查看下面的代码。
const spawn = require('child_process').spawn;
app.post('/upload/audio', function (req, res) {
// Some Code here
// Code to run a child Process
var ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => { // This will run the process and keep receiving the logs as and when available (Async process)
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
// End the Child Process Block
// All the code above is async and will trigger the send way before any of your processes are completed
res.send("Success");
});