包含在可返回的生成器中的nodejs child_process.spawnSync或child_process.spawn返回输出

因为有一段时间我正在努力达到目前为止还没有解决的问题。

使用nodejs,我喜欢在命令退出后运行交互式sh命令并使用sh命令输出。 我喜欢编写一个可收缩的generator函数来封装交互式shell命令的运行并返回shell命令的输出。

方法1:shelljs

  • shelljs
  • 我用shelljs取得了一些成功,但是在某些时候它不会跑得更远。
  • 问题1:是否有可能获得shelljs到我可以inheritancestdio并使shelljs函数可屈服的点?

方法2:child_process.spawnSync

  • child_process.spawnSync
  • 最后我发现了child_process.spawnSync并很高兴,至less我可以运行交互式sh命令而不会出现任何问题options: { stdio: 'inherit' }
  • 但我还没有find如何取回child_process.spawnSync的输出。
  • 问题2:如何将spawnSync封装到返回child_process输出的生成器函数中?

方法3:共同子女过程

  • 我也试过共同子女的过程 。
  • 它似乎运行,但不与stdio互动。 有这个问题 ,我真的不明白。
  • 问题3:有人可以解释我/发表一个例子如何共同subprocess将与stdioinheritance工作。

方法4:用蓝鸟promisify child_process.spawn()

  • 我打开蓝鸟的问题 ,如果child_process.spawn()是promisifiable

所以我的问题。 有人可以给我一个例子,说明如何运行一个交互式shell命令,该命令可以封装在一个返回shell命令输出的可生成生成器函数中? 我很乐意接受新的方法。

我创build了一个在github上可用的npm模块,你可以将它分叉并贡献。

thx提前。

我发现以下在v5.4.1工作。 在文档NodeJSsubprocess中,它提到了默认为'buffer'的选项编码 。 如果你把这个选项设置为'utf8' ,那么你将得到一个返回结果的string,而不是一个缓冲区。 你可以从spawnSync中得到一个string,因为它是同步的并且阻塞执行,直到命令完成。 下面是一个执行'ls -l / usr'命令并以string对象的forms获取输出的脚本示例:

 #!/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( 警告:有很多东西 :))。