Nodejs child_process.exec:禁用在控制台上打印标准输出

我正在通过nodejs child_process.exec执行映像magick标识命令。 并使用从我的脚本中的标准输出返回的string。

一切工作正常,但调用在控制台打印标准输出,如果服务器没有重新启动,控制台不清除一段时间,控制台变得混乱的标准输出消息。

相关编码:

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

我只想禁用在控制台上打印返回的结果。

尝试这个:

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

这会忽略来自exec命令的stderr,但仍显示错误和正常输出。 进一步的configuration请参阅文档 。

清除控制台就够了。

 process.stdout.write('\033c'); // Clears console 

如果可能的话,仍然希望看到一个答案。

在你的确切情况下,我最好的解决scheme是将stdio设置为“pipe道”,类似于Tobias。

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

结果:

 I got success: lol I got error: rmdir: doesntexistlol: No such file or directory 

注意:subprocess是沉默的

没有任何东西是通过subprocess自己打印到控制台的,但是我们从subprocess中获得完整的stdio和stderr消息

这与指出pipe是默认configuration的文档不一致。 实际上,将stdio设置为pipe会改变行为。