[英]How can I pass stdout from one child process to another child process in nodejs?
当我尝试将标准输出从一个进程传递到另一个进程的标准输入时,我遇到了一个神秘的错误。
// test.js
const child_process = require("child_process");
const proc = child_process.spawn("ls", ["-a"]);
const res = child_process.spawnSync("head", ["-n", "3"], {
stdio: [proc.stdout, "pipe", "pipe"],
});
console.log(res.toString("utf8"));
当我使用节点版本v16.13.1
运行node test.js
时,没有看到ls -a | head -n 3
的结果 ls -a | head -n 3
,我收到以下错误:
node test.js[12920]: c:\ws\src\spawn_sync.cc:932: Assertion `0 && "invalid child stdio type"' failed.
1: 00007FF63F1230AF v8::internal::CodeObjectRegistry::~CodeObjectRegistry+112511
2: 00007FF63F0B2216 DSA_meth_get_flags+65542
3: 00007FF63F0B25D1 DSA_meth_get_flags+66497
4: 00007FF63EFD2C69 v8::internal::wasm::WasmCode::code_comments_offset+35065
...
34: 00007FF63FF63A88 v8::internal::compiler::RepresentationChanger::Uint32OverflowOperatorFor+14472
35: 00007FFE6C787034 BaseThreadInitThunk+20
36: 00007FFE6E642651 RtlUserThreadStart+33
我不允许混合child_process.spawn
和child_process.spawn_sync
吗?
如果我将child_process.spawn_sync
更改为child_process.spawn
,则此方法有效,但我需要命令调用是同步的。
不,您不能混合使用它们,请选择一个:sync(均spawnSync
)或 async(您可以通过async/await
同步执行):
// all sync
const proc = child_process.spawnSync('ls', ['-a']);
const res = child_process.spawnSync('head', ['-n', '3'], {input: proc.stdout });
console.log('sync: res', res.stdout.toString('utf8'));
// all async, await result
const cp = () => {
return new Promise((resolve, reject) => {
const proc = child_process.spawn('ls', ['-a']);
const res = child_process.spawn('head', ['-n', '3']);
// pipe between processes
proc.stdout.pipe(res.stdin);
const buffers = [];
res.stdout.on('data', (chunk) => buffers.push(chunk));
res.stderr.on('data', (data) => {
console.error(`stderr: ${data.toString()}`);
reject(data.toString())
});
res.stdout.on('end', () => {
const result = (Buffer.concat(buffers)).toString();
console.log(`done, result:\n${result}`);
resolve(result);
});
});
};
// get results synchronously
(async() => {
console.log('await res:', await cp());
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.