node.js -- 同步执行命令并获取结果 [英] node.js -- execute command synchronously and get result

查看:18
本文介绍了node.js -- 同步执行命令并获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 node.js 中同步执行 child_process(是的,我知道这很糟糕,我有充分的理由)并在 stdout 上检索任何输出,但我不太清楚如何...

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

我发现了这个 SO 帖子:node.js 同步执行系统命令它描述了如何使用库(node-ffi)来执行命令,这很好用,但我唯一能得到的是进程退出代码.该命令执行的任何数据都直接发送到标准输出——我如何捕获它?

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

换句话说,username被echo'd到stdout,run的结果是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

推荐答案

所以我有一个可行的解决方案,但不完全喜欢它......只是在这里发布以供参考:

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

我正在使用其他 SO 帖子中引用的 node-ffi 库.我有一个功能:

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

  • 接受给定的命令
  • 追加>>运行同步输出
  • 执行它
  • 同步读取run-sync-output并存储结果
  • 删除此 tmp 文件
  • 返回结果

有一个明显的问题,如果用户没有对当前目录的写入权限,它就会失败.另外,这只是浪费精力.:-/

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

这篇关于node.js -- 同步执行命令并获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆