Im trying to reduplicate the shelljs exec type execution in node

314 views Asked by At

I was using shelljs before where i used to call a command like so:

require('shelljs/global');

let res = exec('echo hello').stdout

But I would like to achieve this in node without relying on shelljs. Thing is I've found examples with node and I'm having trouble with quite a few of them. Thanks for the help

1

There are 1 answers

0
Matt On BEST ANSWER

The ultra simple answer is use the synchronous version of exec. The stdout won't appear as the command runs and the result won't have the nice properties shelljs provides, just the stdout data

const { execSync } = require('child_process')
const exec = (cmd) => execSync(cmd).toString()
const res = exec('echo "hello there"')

The full shelljs implementation is in exec.js, which runs the command via exec-child.js script to enable the live output + capture to variables for a synchronous exec. It depends on the features you require as to how complex the solution becomes.