📜  Node.js 中 spawn() 和 fork() 方法的区别

📅  最后修改于: 2022-05-13 01:56:34.322000             🧑  作者: Mango

Node.js 中 spawn() 和 fork() 方法的区别

在本文中,我们将讨论 Node.js 中 spawn() 和 fork() 方法之间的区别。两者都是在 Node.js 中创建子进程以处理不断增加的工作负载的方法。

Spawn() 方法: spawn 进程在新进程中启动命令。我们可以将命令作为参数传递给它。 spawn函数的结果是一个实现 EventEmitterAPI 的子流程实例。事件处理程序可以附加或注册到创建的子实例。可以在该子实例上附加或注册的一些事件是断开连接、错误、关闭和消息等。

参数:此方法接受以下参数。

  • 命令:它接受以字符串形式运行的命令。
  • args:它是一个字符串参数列表。默认值为空数组。
  • options:此选项对象可以具有各种属性,例如 stdio、uid、gid、shell 等。
    • shell:接受一个布尔值。如果为 true,则在 shell 内运行命令。可以将不同的 shell 指定为字符串。默认值为 false,表示没有外壳。

返回值:它返回子进程的一个实例。


示例:这是使用 spawn 的一个非常简单且通用的示例。我们首先通过解构要求 spawn,然后通过传递参数创建一个子进程。然后在该子进程上注册一个标准输出事件。

Javascript
const { spawn } = require('child_process');
const child = spawn('dir', ['D:\\empty'], { shell: true });
 
child.stdout.on('data', (data) => {
  console.log(`stdout ${data}`);
});


输出:

由于使用了 fork 子进程,从 child.js 发送的消息正在文件 server.js 中打印。

Spawn 和 Fork 子进程的区别:

Spawn 

Fork

This starts sending data back to a parent process from the child process as soon as the child process starts executing.This does not send data automatically, but we can use a global module name process to send data from the child process and in the parent module, using the name of the child the process to send to the child process.
It creates a new process through command rather than running on the same node process.It makes several individual processes (child processes) but all of them run on the same node process as the parent.
In this, no new V8 instance is created.In this, a new V8 instance is created.
It is used when we want the child process to return a large amount of data back to the parent process.It is used to separate computation-intensive tasks from the main event loop.