以下行将从指定的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.10 , mongoose ,请求和 gridfs-stream 库
答案 0 :(得分:11)
request(url).pipe(fs.createWriteStream(filename)).pipe(writestream);
与此相同:
var fileStream = fs.createWriteStream(filename);
request(url).pipe(fileStream);
fileStream.pipe(writestream);
所以问题在于您尝试将.pipe
一个WriteStream
转换为另一个WriteStream
。
答案 1 :(得分: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);
答案 2 :(得分:3)
我认为链接管道的混乱是由于管道方法隐含地“自行选择”返回管道而引起的。那就是:
readableStream.pipe(writableStream) // Returns writable stream
readableStream.pipe(duplexStream) // Returns readable stream
但是一般规则说“你只能将可写流传输到可读流”。换句话说,只有可读流具有pipe()
方法。