我正在通过nodejs child_process.exec执行图像magick识别命令。并在我的脚本中使用从 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 ) ;
}
Result:
I got success: hello
I got error: rmdir: doesntexist: No such file or directory
注意:子进程是silent
Nothing由子进程本身打印到控制台,但我们可以使用完整的标准输出和标准错误消息。
这与文档*不一致,文档*指出管道是默认配置。实际上,将 stdio 设置为管道会改变行为。
* https://nodejs.org/api/child_process.html#child_process_options_stdio https://nodejs.org/api/child_process.html#child_process_options_stdio
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)