node.js — execute command synchronously and get result

爷,独闯天下 提交于 2019-12-03 13:20:48

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

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.

Logan

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

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

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