Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@droganaida
Last active September 27, 2022 12:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save droganaida/52ba39025d1a90138d2de41812abaf35 to your computer and use it in GitHub Desktop.
Save droganaida/52ba39025d1a90138d2de41812abaf35 to your computer and use it in GitHub Desktop.
Node.js child_process demo. Test for exec(), execFile() and spawn().
const childProcess = require('child_process');
function execProcess(command) {
childProcess.exec(command, function(error, stdout, stderr) {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`error: ${error}`);
}
});
}
function execFile(command, args) {
childProcess.execFile(command, args, function(error, stdout, stderr) {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`error: ${error}`);
}
});
}
function spawnProcess(command, args) {
const s_process = childProcess.spawn(command, args);
let fullData = '';
let dataChunks = 0;
s_process.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
s_process.stdout.on('data', function (data) {
fullData += data;
dataChunks += 1;
console.log(`stdout: ${data}`);
});
s_process.stdout.on('end', function () {
console.log(`end: ${fullData}`);
console.log(`chunks: ${dataChunks}`);
});
s_process.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
}
execProcess('node -v');
// execFile('node', ['-v']);
// spawnProcess('node', ['-v']);
// execFile('ls', ['-l', '/tmp']);
// execProcess('ls -l /tmp');
// spawnProcess('ls', ['-l', '/tmp']);
//----------- the longest article on wikipedia ------------//
// execProcess('curl https://en.wikipedia.org/wiki/List_of_2017_albums');
// execFile('curl', ['https://en.wikipedia.org/wiki/List_of_2017_albums']);
// spawnProcess('curl', ['https://en.wikipedia.org/wiki/List_of_2017_albums']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment