gpt4 book ai didi

javascript - Node child_process.exec : Disable printing of stdout on console

转载 作者:搜寻专家 更新时间:2023-10-31 23:00:46 26 4
gpt4 key购买 nike

我正在通过 nodejs child_process.exec 执行图像魔术识别命令。并在我的脚本中使用从 stdout 返回的字符串。

一切正常,但调用会在控制台上打印 stdout 消息,如果服务器未重新启动且控制台在一段时间内未被清除,则控制台会因 stdout 消息而变得困惑。

相关代码:

var exec = require('child_process').exec;
exec('identify -verbose '+originalFilePath,function(err,stdout,stderr){
var strOut = stdout; // Do something with stdout
});

我只是想禁止在控制台打印返回结果。

最佳答案

在您的确切情况下,我最好的解决方案是将 stdio 设置为“管道”。这正是您想要的。

const execSync = require('child_process').execSync;
try {
let options = {stdio : 'pipe' };
let stdout = execSync('echo hello' , options);
console.log("I got success: " + stdout);
execSync('rmdir doesntexist' , options);//will exit failure and give stderr
} catch (e) {
console.error("I got error: " + e.stderr ) ;
}

结果:

I got success: hello
I got error: rmdir: doesntexist: No such file or directory

注意:子进程静默

没有被子进程自己打印到控制台,但我们得到完整的 stdout 和 stderr 消息来处理。

这与说明管道是默认配置的文档*不一致。实际上,将 stdio 设置为管道会改变行为。


* https://nodejs.org/api/child_process.html#child_process_options_stdio

关于javascript - Node child_process.exec : Disable printing of stdout on console,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25340875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com