Node.js - execute the command synchronously and get the result

I am trying to execute child_process synchronously in node.js (Yes, I know this is bad, I have a good reason) and get any output on stdout, but I cannot figure out how to do this ...

I found this SO: node.js entry to execute the system command synchronously , which describes how to use the library (node ​​-ffi) to execute the command, and this works fine, but the only thing I can get is the process exit code. Any data that the command executes is sent directly to stdout - how to do it?

> run('whoami') username 0 

in other words, username is echoed for stdout, the result of run is 0 .

I would understand a lot how to read stdout

+7
command synchronous
Aug 24 2018-11-21T00:
source share
5 answers

So, I have a solution, but not quite so ... Just send here for reference:

I am using the node-ffi library specified in another SO post. I have a function that:

  • accepts the given command
  • adds >> run-sync-output
  • fulfills it
  • reads run-sync-output synchronously and saves the result
  • deletes this tmp file
  • returns the result

There is an obvious problem when, if the user does not have write access to the current directory, he will fail. Also, this is just a wasted effort .: - /

+2
Aug 24 '11 at 23:17
source share

I built a node.js module that solves this exact problem. Check this:)

exec-plan

Update

The above module solves your original problem as it allows you to synchronize child processes synchronously. Each link in the chain receives stdout from the previous process in the chain.

+1
Sep 23
source share

I had a similar problem and ended up writing a node extension for it. You can check out the git repository. It is open source and free, and all is good!

https://github.com/aponxi/npm-execxi

ExecXI is a node extension written in C ++ to execute shell commands one by one, output the command to the console in real time. Optional chain and unbound methods are present; bearing in mind that you can stop the script from stopping after a command failure (chain), or you can continue as if nothing had happened!

Instructions for use are in the ReadMe file . Feel free to make pull requests or send questions!

However, it still does not return stdout ... Well, I just released it today. Maybe we can do it.

In any case, I thought it was worth mentioning this. I also posted this to a similar question: node.js execute the system command synchronously

+1
Feb 28 '13 at 7:26
source share

Starting with Node v0.11.12, there is a function child_process.execSync for this.

0
Apr 19 '19 at 9:23
source share

Besides writing code a little different, there really is no reason for synchronization.

What do not you like? ( docs )

 var exec = require('child_process').exec; exec('whoami', function (error, username) { console.log('stdout: %s', username); continueWithYourCode(); }); 
-2
Oct 12 '11 at 10:15
source share



All Articles