Last active
July 20, 2019 10:11
-
-
Save ancs21/f018999e70d49df431bb8dbd2743ebcf to your computer and use it in GitHub Desktop.
Promise with shell in Node.js
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
const { exec } = require('child_process') | |
/** | |
* Executes shell command and return as a Promise. | |
* @param cmd {string} | |
* @return {Promise<string>} | |
*/ | |
const execShell = cmd => { | |
return new Promise((resolve, reject) => { | |
exec(cmd, (error, stdout, stderr) => { | |
if (error) { | |
console.warn(error) | |
} | |
resolve(stdout ? stdout : stderr) | |
}) | |
}) | |
} | |
// use | |
execShell('ls -al') | |
.then(d => console.log(d)) | |
.catch(e => console.log(e)) | |
// Credit: | |
// https://nodejs.org/api/child_process.html | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise | |
// https://medium.com/@ali.dev/how-to-use-promise-with-exec-in-node-js-a39c4d7bbf77 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment