【问题标题】:Spawn and kill node.js child processes in different routes hapi.js在不同的路由 hapi.js 中生成和杀死 node.js 子进程
【发布时间】:2019-07-18 18:16:58
【问题描述】:

我有两条路由的 hapi.js 服务器。其中一个应该产生一些子进程,另一个应该杀死它。

var someFunc = require('./module.someFunc')

const Hapi = require('@hapi/hapi');

const { spawn } = require('child_process');

let child

const init = async () => {

 server.route({
  method: 'POST',
  path:'/start',
  handler: (request,h) => {
   child = spawn(someFunc());
  }
 })

 server.route({
  method: 'POST',
  path:'/stop',
  handler: (request,h) => {
   child.kill('SIGINT');
  }
 })
 await server.start();
}

init();

但由于某种原因,我在控制台中出现错误:

TypeError: Cannot read property 'kill' of undefined

UPD:我在触发子进程时也遇到了错误:

TypeError [ERR_INVALID_ARG_TYPE]: The "file" argument must be of type string. Received type object

【问题讨论】:

  • 确保您事先已触发/start。另外如果多次调用start会怎样?
  • 您的someFunc() 是否返回了文件路径字符串?
  • @YuryTarabanko 我很确定我已经触发了/start。现在,如果我多次调用它它会多次调用它的函数(我认为创建单独的子进程)。但这只是为了测试目的——当然我想独立控制每个子进程。
  • @AritraChakraborty 实际上 someFunc() 没有返回任何内容 - 它正在使用外部 API 发出请求。还值得一提的是,我在生成子进程时出错 - TypeError [ERR_INVALID_ARG_TYPE]: The "file" argument must be of type string. Received type object

标签: node.js hapijs


【解决方案1】:

这是因为spawn 抛出错误所以child 变量是null;


spawn 需要一个命令,您不能使用 child_process.spawn 执行一个函数。

在您的情况下,您需要创建一个新文件并在那里创建函数并 fork 它。

child.js

while(something){
   do something
}

那么,

const { fork } = require('child_process');
...
server.route({
  method: 'POST',
  path:'/start',
  handler: (request,h) => {
   child = fork('child.js');
  }
 })
...

有关如何使用child_process 模块的一些简单示例和说明请参考this link

【讨论】:

  • 感谢您向我指出fork 方法!停止子进程时我还应该使用child.kill('SIGINT')吗?
  • 是的,它应该可以工作,因为 forkspawn 都返回 child_process 实例。
猜你喜欢
  • 1970-01-01
  • 2017-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
相关资源
最近更新 更多