我全新安装了 Ubuntu 20.04.2(在 mac 上的虚拟机中运行)。
我已经安装了 Node.js v16(通过官方软件 channel )并观察到一个非常奇怪的问题。使用 studio: 'pipe'
生成的子进程不发出任何 stdout
或 stderr
数据。
重现步骤:
child.js
console.log("Some text");
const interval = setInterval(() => {
console.log("Other text")
}, 100)
setTimeout(() => clearInterval(interval), 1000);
main.jsconst childProcess = require('child_process');
const child = childProcess.spawn('node', ['child.js'], { stdio: 'pipe'});
if (child.stdout) {
console.log("Attach std listeners")
child.stdout.on('data', data => console.log("Child stdout:", String(data)));
child.stderr.on('data', data => console.log("Child stderr:", String(data)));
}
child.on('close', (...args) => { console.log("Child closed", args); });
运行node test.js
为我在 Ubuntu 终端中生成以下内容:Attach std listeners
CLOSED [ 0, null ]
(当我在 macOS 上运行它时,我在输出中得到了预期的多个 Child stdout: Other text
)而如果我改变
stdio
至inherit
在主脚本中,子进程的输出被暴露:Some text
Other text
Other text
Other text
Other text
Other text
Other text
Other text
Other text
Other text
Child closed [ 0, null ]
它向我表明子进程运行没有问题,但由于某种原因,没有 stdout
和 stderr
当它的输出应该被管道传输时由一个 child 发出。我检查过的其他 Node.js 版本(v14、v17、v18nightly)也会出现同样的问题
最佳答案
看来问题在于通过 Snap 依赖项管理器(即官方 Ubuntu 软件安装程序)安装 Node.js 时。
然后软件在只读容器中被沙箱化,对其他系统部分的访问受到限制,并且它表明不适用于 Node.js
解决方案:不要通过 Snap 安装 Node.js,而是通过 apt 安装
关于javascript - Ubuntu : Chilld process with piped stdio, 上的 Node.js 不发出标准输出和标准错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71576027/