FrankKai.github.io
FrankKai.github.io copied to clipboard
nodejs创建进程的4种方式
原文链接:Node.js中的进程与线程
原文中spawn,fork,exec,execFile的示例需要补充一下,我把目录结构和代码做了一些调整,更加易读和理解。
./sub_test
sub_spawn_pipe.js
sub_spawn_ipc.js
sub_fork_ipc.js
sub_exec.js
sub_execFile.js
./test
sub_process.js
spawn进程(流方式通信,on('data'))
sub_spawn_pipe.js
let { spawn } = require("child_process");
let path = require("path");
// 通过node命令执行sub_process.js文件
let childProcess = spawn("node", ["sub_process.js"], {
cwd: path.resolve(__dirname, "test"),
stdio: ["pipe"], // 通过流的方式
});
// 子进程读取写入的数据
childProcess.stdout.on("data", function (data) {
console.log(data.toString()); // 接收到的data是Buffer流,需要通过toString()转为字符串
});
./test/sub_process.js
process.stdout.write('hello');
node ./sub_test/sub_spawn_pipe.js
spawn进程(ipc方式通信, on('message'), send)
sub_spawn_ipc.js
let { spawn } = require("child_process");
let path = require("path");
// 通过node命令执行sub_process.js文件
let childProcess = spawn("node", ["sub_process.js"], {
cwd: path.resolve(__dirname, "test"),
stdio: ["pipe", "pipe", "pipe", "ipc"], // 通过流的方式
});
// 监听消息
childProcess.on("message", function (data) {
console.log(data);
});
./test/sub_process.js
process.send("send");
node ./sub_test/sub_spawn_ipc.js
fork进程(ipc方式通信,on('message'), send)
sub_fork_ipc.js
let { fork } = require("child_process");
let path = require("path");
// 通过node命令执行sub_process.js文件
let childProcess = fork("sub_process.js", {
cwd: path.resolve(__dirname, "test"),
});
childProcess.on("message", function (data) {
console.log(data);
});
./test/sub_process.js
process.send("send");
node ./sub_test/sub_fork_ipc.js
exec
sub_exec.js
const { exec } = require("child_process");
let childProcess = exec(
"node './test/sub_process'",
function (err, stdout, stdin) {
console.log(stdout);
}
);
./test/sub_process.js
process.stdout.write('hello');
node ./sub_test/sub_exec.js
execFile
sub_execFile.js
const { execFile } = require("child_process");
let childProcess = execFile(
"node",
["./test/sub_process"],
function (err, stdout, stdin) {
console.log(stdout);
}
);
./test/sub_process.js
process.stdout.write('hello');
node ./sub_test/sub_execFile.js
总结
- Node的特点是单线程的,一个进程只开启一个主线程。通常来说,是通过多线程来充分利用多核cpu的计算能力。但是Node没有多线程,多核cpu计算能力无法利用了吗?当然不是。一个进程中没有多线程,开多个进程就是多线程了
- 无论是fork,exec还是execFile,本质上都是调用spawn去衍生出进程的
- 进程间的通信方式,是根据child_process.spawn(command[,args][,options])中options的stdio进行设置的