Я хочу записать вывод cmd в файл вместо stdout - PullRequest
0 голосов
/ 24 октября 2019

Я могу cmd в node.js, используя child-process и spawn, я хочу, чтобы выходные данные этой команды записывались в файл вместо 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();

});

Ответы [ 2 ]

1 голос
/ 24 октября 2019

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.

0 голосов
/ 24 октября 2019
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: захват STDOUT `child_process.spawn`

...