Reputation: 2729
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();
});
Upvotes: 0
Views: 684
Reputation: 2729
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`
Upvotes: 0
Reputation: 2371
stdio
option passes 3 "files":
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.
Upvotes: 1