nodejs派生没有构造有效的vim命令



如果我在节点中有这个脚本,则保存为example.js:

const childProcess = require('child_process');
childProcess.spawn('vim', ['-u NONE', 'test.txt'], { stdio: 'inherit' });

我预计node example.js(大致(相当于调用:

vim -u NONE test.txt

然而,当我执行脚本时,我得到:

$ node example.js
VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Dec 26 2020 07:37:17)
Garbage after option argument: "-u NONE"
More info with: "vim -h"

直接运行vim -u NONE example.txt就可以了。

我是否误解/滥用spawn

编辑

这在没有-u NONE标志的情况下运行得很好:

childProcess.spawn('vim', ['test.txt'], { stdio: 'inherit' });

由于某种原因,它添加了vim不喜欢的-u NONE

这应该能在中工作

const cp = spawn('vim', ['test.txt'], {stdio: ['inherit']})
cp.stdout.pipe(process.stdout)

生成一个附加到const cp的child_process(在此ex中(,此方法流式传输其输出(https://nodejs.org/dist/latest-v14.x/docs/api/child_process.html),所以我们需要使用它。我们将cp.stdout管道传输到parent_process.stdout。这将在其中打开一个新的tty:child_process.stdout

我们可以通过将stdio childProcess.output选项设置为'inherit',并(可选(将childProcess.stderr转发到其自己的childProcess.stdout(它已经由motherProcess继承,因此将自动输出(,使其更简单。

这应该与以前的输出相同

const cp = spawn(
'vim', ['test.txt'], 
{stdio: ['inherit', 'inherit', process.stdout]}
)

要精确运行命令vim -u NONE file.ext。第一个参数是可执行路径,第二个参数是包含要传递给命令的标志的数组。在这个数组中,标志的每个元素(用空格分隔(都必须是数组的一个元素。所以在这种情况下,应该工作

const cp = spawn(
'vim', ['-u', 'NONE', 'test.txt'], 
{stdio: ['inherit', 'inherit', process.stdout]}
)

您可以这样使用它:

const { exec } = require("child-process");
exec('vim -u NONE example.txt', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});

最新更新