Nicolas El Khoury
Nicolas El Khoury

Reputation: 6507

executing shell script commands using nodejs

I am trying to find some good libraries to execute shell script commands using nodejs (ex: rm, cp, mkdir, etc...). There are no recent clear articles about possible packages. I read a lot about exec-sync. But some say it is deprecated. Truly, I am lost, and could not find anything. I tried installing exec-sync, but I received the following error:

npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!  
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.

Do you have any suggestions?

Upvotes: 1

Views: 4369

Answers (1)

DavidDomain
DavidDomain

Reputation: 15293

You could simply use nodes Child Process core module, or at least use it to build your own module.

Child Process

The child_process module provides the ability to spawn child processes in a manner that is similar, but not identical, to popen(3). This capability is primarily provided by the child_process.spawn() function:

In particular the exec() method.

child_process.exec()

spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.

Here the example from the docs.

Spawns a shell then executes the command within that shell, buffering any generated output.

const exec = require('child_process').exec;
exec('cat *.js bad_file | wc -l', (error, stdout, stderr) => {
  if (error) {
    console.error(`exec error: ${error}`);
    return;
  }
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

Upvotes: 4

Related Questions