为什么fs.createReadStream不能pipe多次?
发布于 9 年前 作者 wangyangkobe 7767 次浏览 最后一次编辑是 8 年前 来自 问答

<code>

fs.createReadStream(‘pdf-sample1.pdf’) .pipe(fs.createWriteStream(‘pdf-sample2.pdf’)) .pipe(fs.createWriteStream(‘pdf-sample3.pdf’)) </code>

Error: Cannot pipe. Not readable. at WriteStream.Writable.pipe (_stream_writable.js:162:22) at repl:1:86 at REPLServer.defaultEval (repl.js:132:27) at bound (domain.js:254:14) at REPLServer.runBound [as eval] (domain.js:267:12) at REPLServer.<anonymous> (repl.js:279:12) at REPLServer.emit (events.js:107:17) at REPLServer.Interface._onLine (readline.js:214:10) at REPLServer.Interface._line (readline.js:553:8) at REPLServer.Interface._ttyWrite (readline.js:830:14)

5 回复

这样可以:

var f = fs.createReadStream('...') 
f.pipe(fs.createWriteStream('...'))
f.pipe(fs.createWriteStream('...')

你那样不行的原因是,第一次pipe后,返回的类型是WriteStream ,而不再是ReadStream .看看:

f.pipe(fs.createWriteStream('readme2.md')).constructor
>{ [Function: WriteStream]

@1000copy 说的有道理。

一楼正解

只有Duplex类型才能连续pipe,比如zlib.createGzip()socket

回到顶部