Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js -- execute command synchronously and get result

I'm trying to execute a child_process synchronously in node.js (Yes, I know this is bad, I have a good reason) and retrieve any output on stdout, but I can't quite figure out how...

I found this SO post: node.js execute system command synchronously that describes how to use a library (node-ffi) to execute the command, and this works great, but the only thing I'm able to get is the process exit code. Any data the command executes is sent directly to stdout -- how do I capture this?

> run('whoami')
username
0

in otherwords, username is echo'd to stdout, the result of run is 0.

I'd much rather figure out how to read stdout

like image 793
Nobody Avatar asked Aug 24 '11 22:08

Nobody


People also ask

Can NodeJS be synchronous?

For synchronous programming, you only need to focus on the call stack. This is the only part of the NodeJS environment that will be working in this case. A callback stack is a data structure that you use to keep track of the execution of all functions that will run inside the program.

How do you execute a node JS command?

Node. js can run shell commands by using the standard child_process module. If we use the exec() function, our command will run and its output will be available to us in a callback. If we use the spawn() module, its output will be available via event listeners.


1 Answers

So I have a solution working, but don't exactly like it... Just posting here for reference:

I'm using the node-ffi library referenced in the other SO post. I have a function that:

  • takes in a given command
  • appends >> run-sync-output
  • executes it
  • reads run-sync-output synchronously and stores the result
  • deletes this tmp file
  • returns result

There's an obvious issue where if the user doesn't have write access to the current directory, it will fail. Plus, it's just wasted effort. :-/

like image 85
Nobody Avatar answered Oct 17 '22 17:10

Nobody