【发布时间】:2025-12-05 09:10:01
【问题描述】:
我有一个 nodejs 父进程启动另一个 nodejs 子进程。子进程执行一些逻辑,然后将输出返回给父进程。输出很大,我正在尝试使用管道进行通信,正如 child.send() 方法的文档中所建议的那样(顺便说一句,它工作得很好)。
我希望有人建议如何正确建立此沟通渠道。我希望能够从父母向孩子发送数据,也希望能够从孩子向父母发送数据。我已经开始了一点,但它不完整(仅从父母向孩子发送消息)并引发错误。
父文件代码:
var child_process = require('child_process');
var opts = {
stdio: [process.stdin, process.stdout, process.stderr, 'pipe']
};
var child = child_process.spawn('node', ['./b.js'], opts);
require('streamifier').createReadStream('test 2').pipe(child.stdio[3]);
子文件代码:
var fs = require('fs');
// read from it
var readable = fs.createReadStream(null, {fd: 3});
var chunks = [];
readable.on('data', function(chunk) {
chunks.push(chunk);
});
readable.on('end', function() {
console.log(chunks.join().toString());
})
上面的代码打印了预期的输出(“test 2”)以及以下错误:
events.js:85
throw er; // Unhandled 'error' event
^
Error: shutdown ENOTCONN
at exports._errnoException (util.js:746:11)
at Socket.onSocketFinish (net.js:232:26)
at Socket.emit (events.js:129:20)
at finishMaybe (_stream_writable.js:484:14)
at afterWrite (_stream_writable.js:362:3)
at _stream_writable.js:349:9
at process._tickCallback (node.js:355:11)
at Function.Module.runMain (module.js:503:11)
at startup (node.js:129:16)
at node.js:814:3
完整答案:
家长代码:
var child_process = require('child_process');
var opts = {
stdio: [process.stdin, process.stdout, process.stderr, 'pipe', 'pipe']
};
var child = child_process.spawn('node', ['./b.js'], opts);
child.stdio[3].write('First message.\n', 'utf8', function() {
child.stdio[3].write('Second message.\n', 'utf8', function() {
});
});
child.stdio[4].pipe(process.stdout);
孩子的密码:
var fs = require('fs');
// read from it
var readable = fs.createReadStream(null, {fd: 3});
readable.pipe(process.stdout);
fs.createWriteStream(null, {fd: 4}).write('Sending a message back.');
【问题讨论】:
-
你能包括它抛出的错误吗?
标签: node.js pipe child-process