node.js 管道到标准输出和可写流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17822437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:06:41  来源:igfitidea点击:

Pipe to stdout and writeable stream

node.jsnode.js-stream

提问by Nick Tomlin

I'm piping a file through a duplex string (courtesy of through) and I'm having trouble printing information to stdoutandwriting to the file. One or the other works just fine.

我正在通过双工字符串(由through 提供)传输文件,但在向文件打印信息stdout向文件写入信息时遇到问题。一个或另一个工作得很好。

var fs = require('fs');
var path = require('path');
var through = require('through'); // easy duplexing, i'm young


catify = new through(function(data){
    this.queue(data.toString().replace(/(woof)/gi, 'meow'));
});

var reader = fs.createReadStream('dogDiary.txt'); // woof woof etc.
var writer = fs.createWriteStream(path.normalize('generated/catDiary.txt')); // meow meow etc.

// yay!
reader.pipe(catify).pipe(writer)

// blank file. T_T
reader.pipe(catify).pipe(process.stdout).pipe(writer) 

I'm assuming this is because process.stdoutis a writeable stream, but I'm not sure how to do what I want (i've tried passing {end: false}to no avail).

我假设这是因为process.stdout是一个可写的流,但我不确定如何做我想做的事情(我试过传递{end: false}无济于事)。

Still struggling to wrap my head around streams, so forgive me if i've missed something obvious : )

仍在努力将我的头环绕在溪流中,所以如果我错过了一些明显的东西,请原谅我:)

回答by Jonathan Ong

I think what you want is:

我想你想要的是:

reader.pipe(catify)
catify.pipe(writer)
catify.pipe(process.stdout)

These needed to be separated because pipes return their destinations and not their source.

这些需要分开,因为管道返回它们的目的地而不是它们的源。