How to use Promise with exec in Node.js

How to use Promise with exec in Node.js

/**
* Executes a shell command and return it as a Promise.
* @param cmd {string}
* @return {Promise<string>}
*/
function execShellCommand(cmd) {
const exec = require('child_process').exec;
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.warn(error);
}
resolve(stdout? stdout : stderr);
});
});
}

Example usage: check if Java is installed on the device using Node

const javaInfo = await execShellCommand('java -version');
console.log(javaInfo);
/* Prints out:
java version "1.6.0_27"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.6.0_27-b07)
Java HotSpot(TM) Client VM (build 1.6.0_27-b13, mixed mode, sharing)
*/

Conclusion

Senior Software Engineer @LeanIX. Co-founder of Sedeo. Passion for software engineering and startups. Looking forward to build great things. 有難うございます。🚀

Senior Software Engineer @LeanIX. Co-founder of Sedeo. Passion for software engineering and startups. Looking forward to build great things. 有難うございます。🚀