UNPKG

1.45 kBJavaScriptView Raw
1// modified from https://gist.github.com/davidrleonard/2962a3c40497d93c422d1269bcd38c8f
2const shell = require("shelljs");
3
4/**
5 Asynchronously executes a shell command and returns a promise that resolves
6 with the result.
7
8 The `opts` object will be passed to shelljs's `exec()` and then to Node's native
9 `child_process.exec()`. The most commonly used opts properties are:
10
11 - {String} cwd - A full path to the working directory to execute the `cmd` in
12 - {Boolean} silent - If `true`, the process won't log to `stdout`
13
14 See shell.js docs: https://github.com/shelljs/shelljs#execcommand--options--callback
15 See Node docs: https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
16
17 @example
18
19 const execAsync = require('execAsync');
20 execAsync('ls -al', { silent: true, cwd: '/Users/admin/' });
21
22 @param {String} cmd - The shell command to execute
23 @param {Object} opts - Any opts to pass in to exec (see shell.js docs and Node's native `exec` documentation)
24 @returns {String.<Promise>} - Resolves with the command results from `stdout`
25 @private
26**/
27function execAsync(cmd, opts = {}) {
28 return new Promise((resolve, reject) => {
29 shell.exec(cmd, opts, (code, stdout, stderr) => {
30 if (code !== 0) return reject(new Error(stderr.length ? stderr : stdout), code);
31 return resolve(stdout);
32 });
33 });
34}
35
36module.exports = execAsync;