0

I can cmd in node.js using child-process and spawn, I want the ouput of this command to be written into file instead of 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();

});
karansys
  • 2,449
  • 7
  • 40
  • 78
  • Possible duplicate of [Writing files in Node.js](https://stackoverflow.com/questions/2496710/writing-files-in-node-js) – Justin Oct 24 '19 at 13:38
  • does it not works? `let options = ['-h', '>', 'temp.log'];` @Justin how is this a duplication? he wants to know how he gets the output of the child process in a file, not how to write in a file – Scriptkiddy1337 Oct 24 '19 at 13:38
  • thnaks for your reply , the first command to .exe is not built -in one, it can take only -h option, how I am able to write it to file, I willl submit as answer – karansys Oct 24 '19 at 13:46

2 Answers2

1

stdio option passes 3 "files":

  • input
  • output
  • error output

If you want to pipe regular output to a file, you have to pass the file as second item in 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});

Read more about it at https://nodejs.org/api/child_process.html#child_process_options_stdio.

ahwayakchih
  • 2,101
  • 19
  • 24
0
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!");
}); 
```

Inspired from this post Node.js: Capture STDOUT of `child_process.spawn`

karansys
  • 2,449
  • 7
  • 40
  • 78