15

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

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

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

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

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

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

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

使用以下:Node.js 0.10.10mongooserequestgridfs-stream库。

4

4 回答 4

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

与此相同:

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

所以问题是你正在尝试.pipe一个WriteStream进入另一个WriteStream

于 2013-06-14T03:56:24.450 回答
8
// 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);
于 2016-07-19T10:52:13.173 回答
4

我认为链接管道的混乱是由于管道方法隐含地自行“做出选择”来返回什么。那是:

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

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

于 2014-03-30T14:59:00.170 回答
0

您不能将 链接ReadStream到 ,WriteStream因为后者不是双工的,因此您可以这样做 - 对于 gzip 压缩的存档

request.get(url, {
        gzip: true,
        encoding: null
    })
    .pipe(fs.createWriteStream(tmpPath))
    .on('close', function() {
        console.info("downloaded %s", tmpPath);
        fs.createReadStream(tmpPath)
            .pipe(gunzip)
            .pipe(fs.createWriteStream(destPath))
            .on('close', function() {
                console.info("unarchived %s", destPath);
            })
            .on('error', (error) => {
                console.warn("gzip error:%@", error);
            })
    })
    .on('error', (error) => {
        console.warn("download error:%@", error);
    })
于 2021-11-18T15:21:19.773 回答