我有一个NPM脚本,它在CLI中运行得很好。我尝试使用fork(),这样它将运行子进程,然后子进程将返回一些数据给父进程。然后使用节点-cron调度程序每天运行它。
当我使用这样一个简单的执行程序时,它就会工作。
parent.js
const cp = require('child_process');
cp.exec("npm run start argument1 argument2", (err, stdout, stderr) => {
console.log('exec',stdout)
});child.js
let data = someCode()
process.stdout.write("data:" + JSON.stringify(data))但是,我无法将数据返回给父级,所以我尝试了以下操作:
parent.js
const cp = require('child_process');
var child = cp.fork("npm run start argument1 argument2", [], { silent: true });
child.on("message", (data) =>{
console.log('data',data)
})child.js
let data = someCode()
process.stdout.write("data:" + JSON.stringify(data))
process.send(res)它甚至不运行脚本,但是它也没有返回任何错误。
编辑:也许它与babel-node有关?下面是package.json的外观:
{
"scripts": {
"start": "babel-node index.js --",
},
"dependencies": {
"@babel/core": "^7.2.2",
"@babel/node": "^7.2.2",
"@babel/preset-env": "^7.3.1",
"axios": "^0.18.0",
"memory-cache": "^0.2.0",
"moment": "^2.24.0",
"node-cron": "^2.0.3",
"puppeteer": "2.0.0",
"puppeteer-firefox": "^0.5.0",
"shelljs": "^0.8.3"
}
}发布于 2020-02-26 13:19:02
分叉应该指向一个文件,而您不需要{silent:true},让分叉进程继承父进程stdio。
请查看下面的演示:
parent.js
const {fork} = require('child_process');
var child = fork("./child.js", ['argument1','argument2']);
// send data to child.js
child.send({ hello: 'world' });
// receive data from child.js
child.on("message", (fromChild) =>{
console.log('Incoming data from child.js', fromChild)
});child.js
const someCode = ()=> [1,2,3,4,5,6];
let data = someCode();
// send data to parent.js
process.send({data, custom_arguments: process.argv.slice(2)});
// receive data from parent.js
process.on('message', (fromParent) => {
console.log('Incoming data from parent.js:', fromParent);
});https://stackoverflow.com/questions/60397975
复制相似问题