stream的一个问题
发布于 9 年前 作者 wtcsy 4342 次浏览 最后一次编辑是 8 年前 来自 问答

开始学流 看说明说用pipe 接收一个可读流src并将其数据输出到可写流dst src.pipe(dst) 然后看到说 pipe(dst)方法为返回dst流,这样就可以接连使用多个.pipe() 于是我想写个例子验证下

var fs = require(“fs”); var readerStream = fs.createReadStream(“1.txt”); var writerStream = fs.createWriteStream(“2.txt”); var writerStream3 = fs.createWriteStream(“3.txt”); readerStream .pipe(writerStream) .pipe(writerStream3);

其中1.txt是存在的,运行完之后报告错误了 但是还是生成了2.txt ,3.txt 报错的内容是 (不知道为啥错!)

D:\node\stream>node 1.js

events.js:72 throw er; // Unhandled ‘error’ event ^ Error: Cannot pipe. Not readable. at WriteStream.Writable.pipe (_stream_writable.js:127:22) at Object.<anonymous> (D:\node\stream\1.js:7:3) at Module._compile (module.js:456:26) at Object.Module._extensions…js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:906:3

2 回复

那得流是双向的才行, 比如

readStream.pipe(gzip).pipe(writeStream);

readStream/writeStream 显然都是单向的,这种情况应该是要用:

readStream.pipe(writeStream);
readStream.pipe(writeStream3);

额 原来还有单向流和双向流 学习了!

回到顶部