O comando spawn retorna um fluxo legível, então você precisará canalizar isso para um fluxo gravável para fazer algo útil.
Piping para um arquivo
// the filed module makes simplifies working with the filesystem
var filed = require('filed')
var path = require('path')
var spawn = require('spawn')
var outputPath = path.join(__dirname, 'out.txt')
// filed is smart enough to create a writable stream that we can pipe to
var writableStream = filed(outputPath)
var cmd = path.join(__dirname, 'my_script.bash')
var args = [] // you can option pass arguments to your spawned process
var child = spawn(cmd, args)
// child.stdout and child.stderr are both streams so they will emit data events
// streams can be piped to other streams
child.stdout.pipe(writableStream)
child.stderr.pipe(writableStream)
child.on('error', function (err) {
console.log('an error occurred')
console.dir(err)
})
// code will be the exit code of your spawned process. 0 on success, a positive integer on error
child.on('close', function (code) {
if (code !== 0) {
console.dir('spawned process exited with error code', code)
return
}
console.dir('spawned process completed correctly at wrote to file at path', outputPath)
})
Você precisará instalar o módulo arquivado para executar o exemplo acima
npm install filed
Piping para stdout e stderr
process.stdout e process.stderr são ambos fluxos graváveis, assim você pode canalizar a saída de seu comando gerado diretamente para o console também
var path = require('path')
var spawn = require('spawn')
var cmd = path.join(__dirname, 'my_script.bash')
var args = [] // you can option pass arguments to your spawned process
var child = spawn(cmd, args)
// child is a stream so it will emit events
child.stderr.pipe(process.stderr)
child.stdout.pipe(process.stderr)
child.on('error', function (err) {
console.log('an error occurred')
console.dir(err)
})
// code will be the exit code of your spawned process. 0 on success, a positive integer on error
child.on('close', function (code) {
if (code !== 0) {
console.dir('spawned process exited with error code', code)
return
}
console.dir('spawned process completed correctly at wrote to file at path', outputPath)
})