【问题标题】:Nodejs child_process.exec : Disable printing of stdout on consoleNodejs child_process.exec:在控制台上禁用标准输出的打印
【发布时间】:2014-08-16 14:02:05
【问题描述】:

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

一切正常,但调用会在控制台上打印 stdout msg,如果服务器没有重新启动并且控制台有一段时间没有被清除,控制台就会变得杂乱无章,带有 stdout 消息。

相关代码:

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

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

【问题讨论】:

    标签: javascript node.js exec child-process


    【解决方案1】:

    在您的确切情况下,我最好的解决方案是将 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

    【讨论】:

    • 确认此方法有效/有帮助。正如您所指出的,令人沮丧的是,文档如何说“管道”是默认的。
    【解决方案2】:

    试试这个:

    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,但仍会显示错误和正常输出。更多配置见the doc

    【讨论】:

      【解决方案3】:

      清除控制台就足够了。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-04
        • 2013-07-06
        • 1970-01-01
        • 1970-01-01
        • 2010-11-06
        • 2012-07-31
        • 2012-03-22
        相关资源
        最近更新 更多