disfated disfated - 6 months ago 58
Node.js Question

node.js execute system command synchronously

I need in node.js function

result = execSync('node -v');


that will synchronously execute the given command line and return all stdout'ed by that command text.


ps. Sync is wrong. I know. Just for personal use.


UPDATE

Now we have mgutz's solution which gives us exit code, but not stdout! Still waiting for a more precise answer.

UPDATE

mgutz updated his answer and the solution is here :)

Also, as dgo.a mentioned, there is stand-alone module exec-sync

UPDATE 2014-07-30

ShellJS lib arrived. Consider this is the best choice for now.




UPDATE 2015-02-10

AT LAST! NodeJS 0.12 supports
execSync
natively.

See official docs

Answer

NodeJS 0.12 and IO.js 1.10 now support execSync:

child_process.execSync(command[, options])#

You can now directly do this:

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

and it'll do what you expect. (Defaults to pipe the io results to the parent process). Note that you can also spawnSync now.

Comments