const { spawn } = require('child_process');
const child = spawn('wc');
child.stdin.setEncoding('utf-8');
child.stdin.write("console.log('Hello world')\n");
child.stdin.end()
child.stdout.on('data', data =>
console.log(`child stdout:\n${data}`)
)
child.on('close', code =>
console.log('Closed', code)
)
// or make a simple re-usable module
const run = require('./run')
run('wc', "console.log('Hello world')")
.then(console.log)
.catch(console.log)
const { spawn } = require('child_process');
module.exports = (process, stdin) => new Promise((resolve, reject) => {
const child = spawn(process);
child.stdin.setEncoding('utf-8');
child.stdin.write(stdin + "\n");
child.stdin.end()
child.on('error', err =>
reject(err)
)
var result = ''
child.stdout.on('data', data =>
result += data
)
child.on('close', code =>
code === 0
? resolve(result)
: reject(code)
)
})