gpt4 book ai didi

javascript - 如何在 Node.js 中传输和保存 spawnSync 进程的输出?

转载 作者:搜寻专家 更新时间:2023-10-31 23:26:48 24 4
gpt4 key购买 nike

我同步生成一些命令并想要两件事:

  1. 将其标准输出通过管道传输到 process.stdout。
  2. 将标准输出保存到变量中。

我写了这段代码:

var spawnSync = require('child_process').spawnSync;
var result = spawnSync('ls', [ '-l', '-a' ]);
var savedOutput = result.stdout;

console.log(String(savedOutput));

因此,我将 stdout 存储在 savedOutput 变量中——没关系,然后将其注销。但是我还没有将它通过管道传输到标准输出。如果生成的进程很长并且一个一个地写入字符串,我会长时间看到空白屏幕,最后我会看到整个进程的标准输出。

我添加了管道选项:

var spawnSync = require('child_process').spawnSync;
var result = spawnSync('ls', [ '-l', '-a' ], {
stdio: [ 'ignore', 1, 2 ]
});
var savedOutput = result.stdout;

console.log(String(savedOutput));

衍生进程的标准输出通过管道传输到标准输出——没问题。但是 result.stdout 是空的。

我试过使用流:

var spawnSync = require('child_process').spawnSync;
var stream = require('stream');
var grabber = new stream.Writable();

grabber._write = function(chunk, enc, done) {
console.log('Chunk:');
console.log(String(chunk));
done();
};

var result = spawnSync('ls', [ '-l', '-a' ], {
stdio: [ 'ignore', grabber, 2 ]
});

...但是出现错误:

internal/child_process.js:795
throw new TypeError('Incorrect value for stdio stream: ' +
^

TypeError: Incorrect value for stdio stream: Writable

如果我设置 grabber.fd = 2,我不会收到错误,但子 stdout 会通过管道传输到 stdout 而不是 grabber。

所以。如何将子标准输出保存到变量中并同时将其通过管道传输到标准输出?

最佳答案

有几个可能的解决方案,都涉及spawnSync选项

此代码的实时版本可在 https://repl.it/repls/MundaneConcernedMetric 获得。

const spawnSync = require('child_process').spawnSync;

// WITH NO OPTIONS:
// stdout is here, but is encoded as 'buffer'
const result_noOptions = spawnSync('ls', [ '-l', '-a' ]); // won't print anything
console.log(result_noOptions.stdout); // will print <Buffer ...> on completion

// WITH { encoding: 'utf-8'} OPTIONS:
// stdout is also here, _but only printed on completion of spawnSync_
const result_encoded = spawnSync('ls', [ '-l', '-a' ], { encoding: 'utf-8' }); // won't print anything
console.log(result_encoded.stdout); // will print ls results only on completion

// WITH { stdio: 'inherit' } OPTIONS:
// there's no stdout, _because it prints immediately to your terminal_
const result_inherited = spawnSync('ls', [ '-l', '-a' ], { stdio: 'inherit'}); // will print as it's processing
console.log(result_inherited.stdout); // will print null

除了stdout,还可以获得:pidoutputstdout标准错误状态信号错误

https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options

关于javascript - 如何在 Node.js 中传输和保存 spawnSync 进程的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36067734/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com