简体   繁体   中英

Node.js - get reference to processes spawned by child_process.spawn

Is it possible to somehow find a reference to child processes spawned by current process in node.js? I have some code that uses a third party library that spawns a new process. I would like to find a reference to this process and attach some events to it and react to output.

I want to do something like this.

thirdparty.js

const cp = require('child_process');

function spawn(executable, args, stdio) {
  cp.spawn(executable, args, stdio);
}

module.exports = spawn

main.js

const spawn = require('thirdparty');

spawn()
const child = findTheProcess()
child.stdout.on('data', data => {
  // do stuff
});


child.on('message', data => {
  // do stuff

});

One idea that I had was to override cp.spawn but that sounds horrible.

If you return newly created process in thirdpaty.js you'll be able to reference it in main.js

Modified code to list current directory:

thirdparty.js

const cp = require('child_process');

function spawn(executable, args, stdio) {
  return cp.spawn(executable, args, stdio);
}

module.exports = spawn

main.js

const spawn = require("./thirdparty")

const child = spawn("ls")

child.stdout.on("data", (data) => {
  console.log(data.toString())
})

child.on("message", (data) => {
  console.log(data.toString())
})

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