node.js — execute command synchronously and get result

江枫思渺然 提交于 2019-12-12 07:58:15

问题


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


回答1:


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




回答2:


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

exec-plan

Update

The above module solves your original problem, because it allows for the synchronous chaining of child processes. Each link in the chain gets the stdout from the previous process in the chain.




回答3:


I had a similar problem and I ended up writing a node extension for this. You can check out the git repository. It's open source and free and all that good stuff !

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

ExecXI is a node extension written in C++ to execute shell commands one by one, outputting the command's output to the console in real-time. Optional chained, and unchained ways are present; meaning that you can choose to stop the script after a command fails (chained), or you can continue as if nothing has happened !

Usage instructions are in the ReadMe file. Feel free to make pull requests or submit issues!

However it doesn't return the stdout yet... Well, I just released it today. Maybe we can build on it.

Anyway, I thought it was worth to mention it. I also posted this to a similar question: node.js execute system command synchronously




回答4:


Since Node version v0.11.12, there is a child_process.execSync function for this.




回答5:


Other than writing code a little diferent, there's actually no reason to do anything synched.

What don't you like about this? (docs)

var exec = require('child_process').exec;

exec('whoami', function (error, username) {
    console.log('stdout: %s', username);
    continueWithYourCode();
});


来源:https://stackoverflow.com/questions/7183307/node-js-execute-command-synchronously-and-get-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!