简体   繁体   中英

How to use fork in order to run NPM scripts?

I have an NPM start script that works well from the CLI. I'm trying to use fork() so it will run a child process, then that child process will return some data to the parent. And then use a node-cron scheduler to run it daily.

It works when i use a simple exec like this

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))

But then i cannot get the data back to the parent, so i tried this which does not work:

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)

It's doesn't even run the script, ut it's also not returning any error.

Edit : Maybe it's related to the babel-node ? Here is how the package.json looks:

{
  "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"
  }
}

Fork should point to a file, and you don't need {silent:true} , let the forked process inherit the parents stdio.

Check out the demo below:

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);

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM