簡體   English   中英

如何使用 fork 來運行 NPM 腳本?

[英]How to use fork in order to run NPM scripts?

我有一個在 CLI 中運行良好的 NPM 啟動腳本。 我正在嘗試使用fork()以便它運行一個子進程,然后該子進程將一些數據返回給父進程。 然后使用 node-cron 調度程序每天運行它。

當我使用像這樣的簡單 exec 時它起作用

父.js

const cp = require('child_process');
cp.exec("npm run start argument1 argument2", (err, stdout, stderr) => {
     console.log('exec',stdout)
});

孩子.js

let data = someCode()
process.stdout.write("data:" + JSON.stringify(data))

但是后來我無法將數據返回給父級,所以我嘗試了這個不起作用:

父.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)
})

孩子.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"
  }
}

Fork應該指向一個文件,你不需要{silent:true} ,讓 fork 進程繼承父 stdio。

查看下面的演示

父.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)
});

孩子.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);

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM