【问题标题】:How to stop a process in Express when the request timeouts?请求超时时如何停止 Express 中的进程?
【发布时间】:2020-01-01 00:15:42
【问题描述】:

当请求超时时如何停止 Express 中的进程?

安装“连接超时”
import timeout from 'connect-timeout';

// halt_on_timeout.js

module.exports = function haltOnTimedout(req, res, next) {
  if (!req.timedout) next();
};

昂贵的过程需要超过 30 秒 路线超时,但expensive_long_operation 永远不会停止运行..

route.post(
  'upload_alot_of_content/'
   timeout('30s'),
   haltOnTimedout,
   async (req, res) => {
      const result = await expensive_long_operation();
      if (req.timedout) {
        next('error!')
      }
      res({....})
   })

【问题讨论】:

  • expensive_long_operation() 到底是什么。除非您将它放在另一个进程中,否则您将如何处理尝试取消某些异步进程完全取决于它是什么以及它正在等待什么,这需要很长时间。如果它不是异步的,那么它只会占用 CPU 并且不会运行其他任何东西,因此您必须在内部停止它以运行长时间运行的代码。

标签: node.js express error-handling timeout


【解决方案1】:

没有办法在 nodejs 中任意停止异步进程,但是您可以实现几个选项来实现您想要的。

  1. 您可以在分叉的 nodejs 进程中运行昂贵的_long_操作,然后在超时时终止该进程。
  2. 您可以将成本昂贵的_long_operation 编写为异步C++ 模块,并构建一种允许您中断操作的机制。

【讨论】:

    猜你喜欢
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 2014-04-25
    • 1970-01-01
    • 2013-12-13
    • 2022-12-14
    • 1970-01-01
    相关资源
    最近更新 更多