Requirements
This will require Node.js 7 or later with a support for Promises and Async/Await.
Solution
Create a wrapper function that leverage promises to control the behavior of the child_process.exec
command.
Explanation
Using promises and an asynchronous function, you can mimic the behavior of a shell returning the output, without falling into a callback hell and with a pretty neat API. Using the await
keyword, you can create a script that reads easily, while still be able to get the work of child_process.exec
done.
Code sample
const childProcess = require("child_process");
/**
* @param {string} command A shell command to execute
* @return {Promise<string>} A promise that resolve to the output of the shell command, or an error
* @example const output = await execute("ls -alh");
*/
function execute(command) {
/**
* @param {Function} resolve A function that resolves the promise
* @param {Function} reject A function that fails the promise
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
*/
return new Promise(function(resolve, reject) {
/**
* @param {Error} error An error triggered during the execution of the childProcess.exec command
* @param {string|Buffer} standardOutput The result of the shell command execution
* @param {string|Buffer} standardError The error resulting of the shell command execution
* @see https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
*/
childProcess.exec(command, function(error, standardOutput, standardError) {
if (error) {
reject();
return;
}
if (standardError) {
reject(standardError);
return;
}
resolve(standardOutput);
});
});
}
Usage
async function main() {
try {
const passwdContent = await execute("cat /etc/passwd");
console.log(passwdContent);
} catch (error) {
console.error(error.toString());
}
try {
const shadowContent = await execute("cat /etc/shadow");
console.log(shadowContent);
} catch (error) {
console.error(error.toString());
}
}
main();
Sample Output
root:x:0:0::/root:/bin/bash
[output trimmed, bottom line it succeeded]
Error: Command failed: cat /etc/shadow
cat: /etc/shadow: Permission denied
Try it online.
Repl.it.
External resources
Promises.
child_process.exec
.
Node.js support table.