Skip to content

Instantly share code, notes, and snippets.

@ridvanaltun
Created July 7, 2021 22:43
Show Gist options
  • Save ridvanaltun/120760fcc5a0afa298127c231833e218 to your computer and use it in GitHub Desktop.
Save ridvanaltun/120760fcc5a0afa298127c231833e218 to your computer and use it in GitHub Desktop.
Execute shell commands in Node
import { exec } from 'child_process';

/**
 * Execute simple shell command (async wrapper).
 * @param {String} cmd
 * @return {Object} { stdout: String, stderr: String }
 */
async function sh(cmd) {
  return new Promise(function (resolve, reject) {
    exec(cmd, (err, stdout, stderr) => {
      if (err) {
        reject(err);
      } else {
        resolve({ stdout, stderr });
      }
    });
  });
}

async function main() {
  let {stdout, stderr} = await sh('ls');
  for (let line of stdout.split('\n')) {
	  console.log(`ls: ${line}`);
  }
}

main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment