简体   繁体   中英

How to run bash commands from Node.js and get result

I want to run a bash script on my server using a Node js function and get the result back in Node through a callback. Sample script is as follows -

grep -c "eventName" 111data.csv

Is this possible? I looked at the following module but looks very complex. Does anyone know of a way this can be done?

https://www.npmjs.com/package/bashjs

You can execute a command

const { exec } = require('child_process');

const grep = exec('grep -c "eventName" 111data.csv', function (error, stdout, stderr) {
  if (error) {
    console.log(error.stack);
    console.log('Error code: '+error.code);
    console.log('Signal received: '+error.signal);
  }
  console.log('Child Process STDOUT: '+stdout);
  console.log('Child Process STDERR: '+stderr);
});

grep.on('exit', function (code) {
  console.log('Child process exited with exit code '+code);
});

Just modified the example from the Node.js article . Didn't actually test it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM