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

查看:915
本文介绍了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 post: node.js同步执行系统命令,描述如何使用库(node-ffi)执行命令,这很好,但我能得到的唯一的是过程退出代码。命令执行的任何数据都直接发送到stdout - 我如何捕获这个?

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

c $ c> username 是回声到stdout,运行的结果是 0

in otherwords, username is echo'd to stdout, the result of run is 0.

所以我有一个解决方案工作,但不完全喜欢它... :

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

我使用在其他SO post中引用的 node-ffi 库。我有一个函数:

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


  • 接受给定的命令

  • 追加>>运行同步输出

  • 执行它

  • code>同步并存储结果

  • 删除此tmp文件

  • 返回结果

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

我会 很多 ,而不知道如何读取stdout

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 post中引用的 node-ffi 库。我有一个函数:

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


  • 接受给定的命令

  • 追加>>运行同步输出

  • 执行它

  • code>同步并存储结果

  • 删除此tmp文件

  • 返回结果

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

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

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