简体   繁体   English

Node.js:当命令什么都不返回时,child_process.exec出错

[英]Nodejs: child_process.exec get error when command return nothing

When using child_process.exec in nodejs, it hit an error when the command return nothing. 在nodejs中使用child_process.exec时,该命令不返回任何内容时会出错。 I do following: 我这样做:

const {exec} = require('child_process');

const cmd = `ps -ef | grep -v grep | grep abc123.py`;
exec(cmd, (err, stdout, stderr) => {
    if(err) {
        console.error(`__get error: ${stderr}`);
        return;
    }
    console.log(stdout);
    return;
})

Since 'abc123.py' is not running, it return nothing if run this command directly. 由于“ abc123.py”未运行,因此如果直接运行此命令,则不返回任何内容。 But this code get this: 但是这段代码得到了这个:

__get error:

I meet this error with Node 8.10.0 and 10.16.0 . 我在Node 8.10.0和10.16.0中遇到此错误。 Is there anything I ignored? 有什么我忽略的吗?

You try to exec nonexistent script, so your ps -ef | grep -v grep | grep abc123.py 您尝试执行不存在的脚本,因此您的ps -ef | grep -v grep | grep abc123.py ps -ef | grep -v grep | grep abc123.py ps -ef | grep -v grep | grep abc123.py return 1 as a exit code and write nothing to stderr. ps -ef | grep -v grep | grep abc123.py返回1作为退出代码,并且不向stderr写入任何内容。 From Nodejs.org we know that the Nodejs.org我们知道

Any exit code other than 0 is considered to be an error. 除0以外的任何退出代码均被视为错误。

So, your code works right. 因此,您的代码工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM