0

I am really new to NodeJS and playing around with some functions. I want to use some commands from cmd using Node. My attempt was this here:

const execSync = require('child_process').execSync;
code = execSync('node -v');
console.log(code);

But instead of getting a one-liner, I am getting a whole ChildProcess object like this:

ChildProcess {
    _events: [Object: null prototype] {
    close: [Function: exithandler],
    error: [Function: errorhandler]
  },
  _eventsCount: 2,.....and so on

Can anyone guide me please? Why is that so and how can I do it?

3 Answers 3

1

By default stdout is sent to the parent process. You can set options.stdio if you want it to go elsewhere.

const { execSync } = require('child_process');
const code = execSync('node -v', { stdio: 'inherit' });

console.log(code);
Sign up to request clarification or add additional context in comments.

Comments

1

Just use additional .toString()

execSync('node -v').toString()

The type returned by 'child_process' is Buffer, you want a string.

Remember though, that all the commands executed are ended with the newline \n character.

Full code

const execSync = require('child_process').execSync;
const code = execSync('node -v').toString;
console.log(code);

will give you something like

'v10.15.1\n'

depending on the node version you currently run.

1 Comment

For the record, execSync('node -v').toString(); not execSync('node -v').toString;
0

Executing stuff in Node just isn't that easy, but there is a module that can make it easier. Take a look at shelljs.exec:

const version = exec('node --version', {silent:true}).stdout;

1 Comment

Thank you! I will have a look on that later

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.