js在子进程中运行功能

js在子进程中运行功能

本文介绍了node.js在子进程中运行功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个node.js应用程序,该应用程序通过Web请求接收文件,然后将转换过程应用于此文件。由于任务长时间运行,因此需要与主线程分开运行。



此刻,我刚刚通过 setTimeout调用了必要的代码()调用。为了将主应用程序与转换过程隔离开来,我想将其移到子进程中,因为它运行很长时间,并且我想将主代码与正在完成的工作隔离开(我担心太多了吗?)。目前我正在呼叫:

  const execFile = require(‘child_process’)。execFile; 
const child = execFile('node','./myModule.js',(error,stdout,stderr)= >> {
if(error){
抛出错误;
}
console.log(stdout);
});

在node.js中,这是正确的方法吗?还是只是使用指定模块和参数,但不必将'node'指定为可执行文件?

解决方案

刚刚看到node.js提供了'fork'函数,用于执行模块,尽管它们将需要像期望命令行参数那样编写,并处理process.argv数组。



命令调用正在:

  child_process.fork(modulePath [,args] [,options])

更多详细信息。



在我的特定情况下,分叉可能没有意义,因为我正在使用的node.js库已经在进行分叉。 / p>

I have a node.js application that receives a file, via a web request and then will apply a conversion process to this file. Since the task is long running this needs to run separate to the main thread.

At the moment I have just called the necessary code via a setTimeout() call. To isolate the main application from the conversion process I would like to move it out into a child process, since it is long running and I would like to isolate the main code from the work being done (am I worrying too much?). At the moment I am calling:

const execFile = require('child_process').execFile;
const child = execFile('node', './myModule.js', (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);
});

Is this the right approach in node.js, or is there of simply starting a child process with the module and params specified, but not have to specify 'node' as the executable?

解决方案

Just seen that node.js provides the 'fork' function, for executing modules, though they will need to be written as if they were expecting command line arguments, processing the process.argv array.

The command call being:

child_process.fork(modulePath[, args][, options])

More details here.

In my specific case forking probably doesn't make sense, since there is already a fork being made by the node.js library I am using.

这篇关于node.js在子进程中运行功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:21