在nodejs中如果需要传输大量的、二进制的数据流,还是采用pipe管道形式较为合适。
1、parent.js
const {spawn} = require("child_process");
let cp = spawn("node", ['./child.js'], {stdio : [process.stdin, process.stdout, process.stderr, 'pipe']}); //设定索引3的通道类型为'pipe'
cp.stdio[3].on("data", (data)=>{
//子进程传递过来的数据
console.log(data);
});
cp.stdio[3].write(new Uint8Array([1,2,3])); //向子进程发送二进制数据
2、child.js
const fs = require("fs");
const ws = fs.createWriteStream(null, {fd : 3}); //写句柄,fd号为3
const rs = fs.createReadStream(null, {fd : 3}); //读句柄,fd号为3
rs.on("data", (data)=>{
//父进程传递过来的数据
console.log(data);
});
rw.write(new Uint8Array([4,5,6]));//向父进程发送二进制数据