【问题标题】:I want to write cmd ouput to file instead of stdout我想将 cmd 输出写入文件而不是 stdout
【发布时间】:2019-10-24 13:32:27
【问题描述】:

我可以在 node.js 中使用子进程和 spawn 进行 cmd,我希望将此命令的输出写入文件而不是 stdout。

test.js

const expect = require('chai').expect;
const { spawn } = require('child_process')
let path = require('path');
let fs = require('fs');

//tried but didn't work 
1) const cmd = spawn(ansysfnonetclient, options, {
    stdio: [
      0, // Use parent's stdin for child.
      'pipe', // Pipe child's stdout to parent.
      fs.openSync('err.out', 'w') // Direct child's stderr to a file.
    ]
  });

2)  const cmd = spawn(ansysfnonetclient, options,  {shell: true, stdio: 'inherit'});


it('run the cmd and write o/p to file', function (done) {
  this.timeout(30000); 
 let options = ['-h','-o','temp.log'];

 let ansysfnonetclient = path.resolve(__dirname,'../../../../../../../../saoptest/annetclient.exe');

 const cmd = spawn(ansysfnonetclient, options,  {shell: true, stdio: 'inherit'});
 console.log(cmd);
 done();

});

【问题讨论】:

  • Writing files in Node.js的可能重复
  • 不行吗? let options = ['-h', '>', 'temp.log'];@Justin 这是怎么重复的?他想知道他如何在文件中获取子进程的输出,而不是如何在文件中写入
  • 感谢您的回复,.exe 的第一个命令不是内置命令,它只能采用 -h 选项,我如何将其写入文件,我将提交作为答案

标签: javascript node.js testing npm child-process


【解决方案1】:

stdio 选项传递 3 个“文件”:

  • 输入
  • 输出
  • 错误输出

如果要将常规输出通过管道传输到文件,则必须将文件作为stdio 中的第二项传递:

const { spawn } = require('child_process');
const fs = require('fs');

const stdio = [
  0,
  fs.openSync('std.out', 'w'),
  fs.openSync('err.out', 'w')
];

const child = spawn('echo', ['hello world!'], {stdio});

https://nodejs.org/api/child_process.html#child_process_options_stdio了解更多信息。

【讨论】:

    【解决方案2】:
    const expect = require('chai').expect;
    const { spawn } = require('child_process')
    let path = require('path');
    let fs = require('fs');
    
    ```
    const cmd = spawn(ansysfnonetclient, options,  {shell: true, stdio: 'inherit'});
    
    cmd.stdout.on('data',function(chunk) {
    
    fs.writeFile(path.resolve(__dirname,'../../../../../../../../output.log'), chunk.toString(), function(err) {
    
      if(err) 
      {
        return console.log(err);
      }
    
      console.log("The file was saved!");
    }); 
    ```
    

    灵感来自这篇帖子Node.js: Capture STDOUT of `child_process.spawn`

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 1970-01-01
      • 2010-12-19
      • 1970-01-01
      • 2016-01-31
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 2014-11-04
      相关资源
      最近更新 更多