Skip to content

Instantly share code, notes, and snippets.

@ancs21
Last active July 20, 2019 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ancs21/f018999e70d49df431bb8dbd2743ebcf to your computer and use it in GitHub Desktop.
Save ancs21/f018999e70d49df431bb8dbd2743ebcf to your computer and use it in GitHub Desktop.
Promise with shell in Node.js
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