Search code examples
node.jscommandsynchronous

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


Solution

  • 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. :-/