【问题标题】:Performing work after ending the request in nodejs + express在nodejs + express中结束请求后执行工作
【发布时间】:2016-08-14 16:20:59
【问题描述】:

我想做一些客户端不需要知道的 CPU 处理。我正在考虑使用 https://github.com/audreyt/node-webworker-threads 包来做到这一点(例如,将音频文件从 ogg 转换为 raw)。

我想我可以使用res.send(200),然后像这样启动工人:

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 - 线程,我希望不会。

【问题讨论】:

  • 创建一个 Websocket 并使用您的常规 http 端口来触发 WS,无论更新是什么,它都会不断地告诉前端。这不是一个好主意,但万一此应用程序尝试同时为大量用户提供服务
  • 现在就您的代码而言,res.send 基本上会触发此函数的返回,因为这将是一个回调并且不会再次返回到当前函数。
  • 我不想告诉用户任何事情。
  • 如果是这种情况,则在 2 个端口之间保留一个 Web 套接字。节点在特定端口上运行,另一个特定端口将分配给 WS。否则,您甚至可以从您的代码中触发不同的 URL 来执行此操作
  • 这是否影响主事件循环完全取决于 node-webworker-threads 包的实现。如果它真的使用线程或其他进程,那么你很好。如果它只是看起来使用其他线程,但实际上只是同一进程中的异步代码,那么它将妨碍您处理其他请求。为了确保它在主事件循环中“不碍事”,您可以在子进程中执行工作。

标签: javascript node.js multithreading


【解决方案1】:

您可以创建一个子进程来执行此操作。看看这个Link 了解更多详情。要了解该过程,请查看以下代码。

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");
});

【讨论】:

  • 好吧,这只是一种方式.. 就此而言,如果您在代码中最后编写 res.send,它仍然可以工作..
猜你喜欢
  • 2016-04-27
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多