如何在 Node.js 0.10 中立即使用读取流链接写入流?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17098400/
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 14:46:42  来源:igfitidea点击:

How to chain write stream, immediately with a read stream in Node.js 0.10?

node.jsstreammongoosepipegridfs

提问by Sahat Yalkabov

The following line will download an image file from a specified urlvariable:

以下行将从指定的url变量下载图像文件:

var filename = path.join(__dirname, url.replace(/^.*[\\/]/, ''));
request(url).pipe(fs.createWriteStream(filename));

And these lines will take that image and save to MongoDB GridFS:

这些行将获取该图像并保存到 MongoDB GridFS:

 var gfs = Grid(mongoose.connection.db, mongoose.mongo);
 var writestream = gfs.createWriteStream({ filename: filename });
 fs.createReadStream(filename).pipe(writestream);

Chaining pipelike this throws Error: 500 Cannot Pipe. Not Pipeable.

pipe像这样的链接会引发错误:500 无法管道。不可管道。

request(url).pipe(fs.createWriteStream(filename)).pipe(writestream);

This happens because the image file is not ready to be read yet, right? What should I do to get around this problem?Error: 500 Cannot Pipe. Not Pipeable.

发生这种情况是因为图像文件还没有准备好被读取,对吗?我应该怎么做才能解决这个问题?错误:500 无法管道。不可管道。

Using the following: Node.js 0.10.10, mongoose, requestand gridfs-streamlibraries.

使用下面的:Node.js的0.10.10猫鼬要求GridFS的流库。

回答by loganfsmyth

request(url).pipe(fs.createWriteStream(filename)).pipe(writestream);

is the same as this:

与此相同:

var fileStream = fs.createWriteStream(filename);
request(url).pipe(fileStream);
fileStream.pipe(writestream);

So the issue is that you are attempting to .pipeone WriteStreaminto another WriteStream.

所以问题是你正试图将.pipe一个WriteStream变成另一个WriteStream

回答by BIJENDER KHATANA

// create 'fs' module variable
var fs = require("fs");

// open the streams
var readerStream = fs.createReadStream('inputfile.txt');
var writerStream = fs.createWriteStream('outputfile.txt');

// pipe the read and write operations
// read input file and write data to output file
readerStream.pipe(writerStream);

回答by mechanicious

I think the confusion in chaining the pipes is caused by the fact that the pipe method implicitly "makes choices" on it's own on what to return. That is:

我认为链接管道的混乱是由于管道方法隐式地“做出选择”,它自己决定返回什么。那是:

readableStream.pipe(writableStream) // Returns writable stream
readableStream.pipe(duplexStream) // Returns readable stream

But the general rule says that "You can only pipe a Writable Stream to a Readable Stream." In other words only Readable Streams have the pipe()method.

但一般规则是“您只能通过管道将 Writable Stream 传输到 Readable Stream”。换句话说,只有 Readable Streams 有这个pipe()方法。