What is a node child process?

浪尽此生 提交于 2019-12-11 02:21:42

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/42327180/what-is-a-node-child-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!