有一段时间以来,我一直在尝试达成一些目前对我来说还行不通的事情。
对于 nodejs,我喜欢运行交互式 sh-command 并在命令退出后使用 sh-command 输出。我喜欢编写一个可生成的生成器函数,它包装交互式 shell 命令的运行并返回 shell 命令的输出。
方法一:shelljs
- shelljs
- 我在 shelljs 上取得了一些成功,但在某些时候它不会再运行了。
- 问题 1:是否有可能使 shelljs 达到我可以继承 stdio 并使 shelljs 函数可产生的程度?
方法二:child_process.spawnSync
- child_process.spawnSync
- 最后我发现了 child_process.spawnSync 并且很高兴,至少我可以运行交互式 sh 命令而不会出现问题
options: { stdio: 'inherit' }
- 但我还没有找到如何取回 child_process.spawnSync 的输出。
- 问题 2:如何将 spawnSync 包装到返回 child_process 输出的生成器函数中?
方法 3:co-child-process
- 我也试过co-child-process .
- 它似乎可以运行,但不能与 stdio 交互。有一个issue关于这一点,我真的不明白。
- 问题 3:有人可以向我解释一下/发布一个示例,说明子进程如何与 stdio inherit 一起工作。
方法 4:使用 bluebird promisify child_process.spawn()
- 我打开了一个issue在 bluebird 上,如果 child_process.spawn() 是可 promise 的
所以我的问题。有人可以给我发一个示例,说明如何运行交互式 shell 命令,该命令可以包装在返回 shell 命令输出的可屈服生成器函数中吗?我对新方法持开放态度。
我创建了一个 npm 模块,可在 github 上使用你可以在哪里 fork 它并做出贡献。
提前致谢。
最佳答案
我发现以下适用于 v5.4.1 。在文档中 NodeJS Child Process它提到了选项 encoding,它的默认值为 'buffer'。如果您将此选项设置为 'utf8',那么您将返回一个包含结果的字符串而不是缓冲区。您可以从 spawnSync 取回一个字符串,因为它是同步的并且会在命令完成之前阻止执行。这是执行“ls -l/usr”命令并将输出作为字符串对象获取的脚本的工作示例:
#!/usr/bin/env node
var cp = require('child_process');
var ls = cp.spawnSync('ls', ['-l', '/usr'], { encoding : 'utf8' });
// uncomment the following if you want to see everything returned by the spawnSync command
// console.log('ls: ' , ls);
console.log('stdout here: \n' + ls.stdout);
当你运行它时,你会得到以下信息:
stdout here:
total 68
drwxr-xr-x 2 root root 36864 Jan 20 11:47 bin
drwxr-xr-x 2 root root 4096 Apr 10 2014 games
drwxr-xr-x 34 root root 4096 Jan 20 11:47 include
drwxr-xr-x 60 root root 4096 Jan 20 11:47 lib
drwxr-xr-x 10 root root 4096 Jan 4 20:54 local
drwxr-xr-x 2 root root 4096 Jan 6 01:30 sbin
drwxr-xr-x 110 root root 4096 Jan 20 11:47 share
drwxr-xr-x 6 root root 4096 Jan 6 00:34 src
文档告诉您除了 stdout 之外您还可以从对象上得到什么。如果您想查看返回对象的所有属性,请取消注释 console.log(警告:有很多内容 :))。
关于node.js - nodejs child_process.spawnSync 或 child_process.spawn 包裹在返回输出的可屈服生成器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32393250/