有一段时间以来,我一直在努力达到目前为止对我不起作用的事情。
使用nodejs,我喜欢运行一个交互式sh-命令,并在命令退出后使用sh-命令输出。我喜欢编写一个可屈服的生成器函数,它封装交互式shell命令的运行并返回shell命令的输出。
方法1: shelljs
方法2: child_process.spawnSync
options: { stdio: 'inherit' }的问题。方法3:共子过程
方法4:用蓝知更鸟对child_process.spawn()进行编程
所以我的问题。有人能给我一个例子,说明如何运行一个交互式shell命令,该命令可以包装在一个可折叠的生成器函数中,返回shell命令的输出?我愿意接受新的方法。
我创建了一个可在github上使用的npm模块,您可以在该模块中对其进行分叉和贡献。
提前结束。
发布于 2016-01-20 19:55:42
我发现了在5.4.1版本上工作的以下内容。在docs NodeJS子过程中,它提到了默认的“缓冲区”选项编码。如果将此选项设置为“utf8 8”,则将得到一个返回结果的字符串,而不是缓冲区。您可以从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的注释(警告:有很多内容:)。
https://stackoverflow.com/questions/32393250
复制相似问题