Last active
November 24, 2015 10:45
-
-
Save vitalymak/11f4720c3d12d2dda863 to your computer and use it in GitHub Desktop.
Node.js child_process examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const child_process = require('child_process'); | |
const execCallback = (resolve, reject) => { | |
return (error, stdout, stderr) => { | |
stdout && console.log(stdout); | |
stderr && console.log(stderr); | |
error ? reject(new Error(error)) : resolve(); | |
}; | |
}; | |
const spawnForkCallback = (resolve, reject) => { | |
return (code, signal) => { | |
console.log(`Exited with code: ${code}, signal: ${signal}\n`); | |
code ? reject(new Error(code)) : resolve(); | |
}; | |
}; | |
const file1 = './file1.sh'; | |
const file2 = 'file2.js' | |
Promise.resolve() | |
.then(() => new Promise((resolve, reject) => { | |
const cmd = `echo 'echo "Hello from ${file1}"' > ${file1}; chmod +x ${file1}; echo '${file1} writed'; | |
echo 'console.log("Hello from ${file2}");' > ${file2}; echo '${file2} writed' | |
`; | |
console.log(`We can execute arbitrary command(s) in one string via exec, for example:\n${cmd}`); | |
child_process.exec(cmd, execCallback(resolve, reject)); | |
})) | |
.then(() => new Promise((resolve, reject) => { | |
console.log(`But it's not work with execFile:`); | |
child_process.execFile( | |
file1, // or you can try here `${file1}; echo 'hi'`, failed silently | |
[ | |
';', | |
`echo 'hi'` | |
], | |
execCallback(resolve, reject) | |
); | |
})) | |
.then(() => new Promise((resolve, reject) => { | |
console.log(`And not work with spawn:`); | |
child_process.spawn( | |
file1, // or you can try here `${file1}; echo 'hi'`, will raise error ENOENT | |
[ | |
' > not_be_writed', | |
], | |
{stdio: 'inherit'} | |
).on('exit', spawnForkCallback(resolve, reject)); | |
})) | |
.then(() => new Promise((resolve, reject) => { | |
console.log(`And not work with fork:`); | |
child_process.fork( | |
file2, // or you can try here `${file2}; echo 'hi'`, will raise error "Cannot find module..." | |
[ | |
' > not_writed_too' | |
] | |
).on('exit', spawnForkCallback(resolve, reject)); | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment