node.js 同步执行系统命令 [英] node.js execute system command synchronously
问题描述
我需要 node.js 函数
result = execSync('node -v');
这将同步执行给定的命令行并返回该命令文本的所有标准输出.
that will synchronously execute the given command line and return all stdout'ed by that command text.
ps.同步错误.我知道.仅供个人使用.
ps. Sync is wrong. I know. Just for personal use.
更新
现在我们有了 mgutz 的解决方案,它为我们提供了退出代码,但没有标准输出!仍在等待更准确的答案.
Now we have mgutz's solution which gives us exit code, but not stdout! Still waiting for a more precise answer.
更新
mgutz 更新了他的答案,解决方案就在这里:)
另外,正如 dgo.a 所提到的,有一个独立的模块 exec-同步
mgutz updated his answer and the solution is here :)
Also, as dgo.a mentioned, there is stand-alone module exec-sync
更新 2014-07-30
ShellJS 库到了.认为这是目前最好的选择.
ShellJS lib arrived. Consider this is the best choice for now.
更新 2015-02-10
终于!NodeJS 0.12 原生支持 execSync
.
查看官方文档
AT LAST! NodeJS 0.12 supports execSync
natively.
See official docs
推荐答案
Node.js(从 0.12 版开始 - 所以有一段时间)支持 execSync
:
Node.js (since version 0.12 - so for a while) supports execSync
:
child_process.execSync(command[, options])
您现在可以直接执行此操作:
You can now directly do this:
const execSync = require('child_process').execSync;
code = execSync('node -v');
它会做你所期望的.(默认将 i/o 结果通过管道传输到父进程).请注意,您现在也可以spawnSync
.
and it'll do what you expect. (Defaults to pipe the i/o results to the parent process). Note that you can also spawnSync
now.
这篇关于node.js 同步执行系统命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!