简体   繁体   中英

What is a node child process?

I'm reading a node.js project which includes the child_process library.

What exactly is a child process? Is this similar a javascript web worker?

What advantages are there to running processes in a child process rather than simply executing it normally? I'm assuming this some how gives you more access to memory?

When you run terminal on Linux (bash process), and execute a command, for example ls -lh /usr , the terminal starts a child process ls , that writes to stdout all files in the current directory. Now image that instead of a terminal, you have node.js as a parent process. You can spawn/start a child ls process like this:

const spawn = require('child_process').spawn;
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

Is this similar a javascript web worker?

It might be similar to webworkers, but I don't know how webworkers are implemented under the hood in browsers. AFAIK node doesn't have webworkers API out of the box. But if your child process is node.js process, than you can view this child process something akin to webworker . Take a look at this cluster API .

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