[在Node中使用child_process.spawn
时,它会生成一个子进程并自动创建stdin,stdout和stderr流以与chil进行交互。
const child = require('child_process');
const subProcess = child.spawn("python", ["myPythonScript.py"])
subProcess.stdout.on('data', function(data) {
console.log('stdout: ' + data);
});
因此,在我的项目中实现了这一点,但事实是,子进程仅在缓冲区达到一定大小时才实际在输出流上写入。而不是当缓冲区设置有数据(无论数据大小如何)时。确实,我想在子流程输出流写入输出流时直接接收它,而不是在它填满整个缓冲区时接收。任何解决方案?
我认为您需要readline
。
const fs = require('fs');
const readline = require('readline');
async function processLineByLine() {
const fileStream = fs.createReadStream('input.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
}
}
processLineByLine();
来自https://nodejs.org/api/readline.html#readline_example_read_file_stream_line_by_line