node.js - 有没有任何编程方法可以打破 NodeJS 中的无限循环?

标签 node.js asynchronous process infinite-loop

最终来说 - 是否有一种实用的方法(也可能通过在代码中插入一些 JS 结构)来在执行过程中中断或停止持久的 JS 代码?例如:它可以被某些 process.* 对象结构或类似的结构中断吗?还是其他方式?有效的解决方案甚至可能包括要终止和/或重新启动的 NodeJS 进程。谢谢!

编辑: 我需要使用 Function 子句(ala eval,-更不用说安全问题了)在服务器上执行一些特定的用户代码。我无法在其中插入任何额外的代码,只能将其括起来。我需要的是有可能在 5 分钟后破解用户代码(如果此时尚未完成)。例如:

usercode = 'Some code from the user';
pre_code = 'some controlling code for breaking the user code';
post_code = 'another controlling code';

fcode = pre_code + usercode + post_code;

<preparations for breaking usercode>

(new Function(fcode))(); // This MUST exit in 5 minutes

最佳答案

编辑:

回答您的编辑。我现在明白了这个意图。如果它在nodejs中运行,您可以使用worker_thread https://nodejs.org/api/worker_threads.html#worker_threads_worker_workerdata .

例如:

// main.js
const runCode = (code) => { 
  const worker = new Worker("./code-executor.js", { workerData: { code: guestCode } });
  const promise = new Promise((resolve) => {
    setTimeout(() => worker.kill(), 60000 * 5);
    worker.on("error", () => {
      return reject(new SomeCustomError())
    });
    worker.on("message", (message) => {
      if(message.success) return resolve(message.result);
      return reject(new Error(message.error));
    });
  });

  promise.finally(() => { worker.kill() });

  return promise;
}

// code-executor.js

const { workerData, parentPort } = require("worker_threads");
const { code } = workerData;

Promise.resolve()
 .then(() => (new Function(fcode))())
 .then((result) => {
   parentPort.postMessage({
     success: true,
     result: value
   })
 })
 .catch((error) => {
   parentPort.postMessage({
     success: true,
     error: error.message
   })
 });

如果在浏览器中https://developer.mozilla.org/en-US/docs/Web/API/Worker WebAPI不完全相同,但逻辑应该类似

原创

终止进程。另请阅读:https://nodejs.org/api/process.html#process_signal_events

process.kill(pid, "SIGINT")

“杀死”一个长时间运行的函数,你必须破解一下。没有优雅的解决方案。注入(inject)一个可以在长期运行函数之外发生变化的 Controller 。要从外部停止它,请设置 controller.isStopped = true


export const STOP_EXECUTION = Symbol();

function longRunning(controller){
  ... codes

  // add stopping point
  if(controller.isStopped) throw STOP_EXECUTION;

  ... codes

  // add stopping point
  if(controller.isStopped) throw STOP_EXECUTION;

  ... codes
}

// catch it by 

try{
  longRunnning();
}catch(e){
  switch(true){
    e === STOP_EXECUTION: ...;  // the longRunning function is stopped from the outside
    default: ...;               // the longRunning function is throwing not because of being stopped 

  }
}

要点:https://gist.github.com/Kelerchian/3824ca4ce1be390d34c5147db671cc9b

关于node.js - 有没有任何编程方法可以打破 NodeJS 中的无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60623418/

相关文章:

javascript - Axios:基本身份验证不适用于 GET 请求

ios - 在后台线程上访问 UIView 的属性

wcf - Silverlight 应用程序能否从一个调用接收多个回调?

node.js - 为什么我的 AWS Lambda 函数返回 "Invalid JSON"错误?

javascript - 如何使用客户端 session 持续时间和 activeDuration 使 session 持续最多 30 天

javascript - 是否可能有多个未完成的异步请求?

python - 在 Python 中杀死一个程序

c++ - 如何在 C++ 任务管理器上更改进程的名称?

multithreading - 进程与线程的例子

javascript - 如果需要在 rethinkdb 中创建数据库