猿问

我想将 cmd 输出写入文件而不是 stdout

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


测试.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();


});


慕侠2389804
浏览 162回答 2
2回答

慕无忌1623718

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阅读更多相关信息。

慕标5832272

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!");}); ```
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答