我是 Node.js 的新手.谁能为我提供一个示例,说明如何使用 GridFS 存储和检索二进制数据,例如使用 Node.js 和 Mongoose 的图像?我需要直接访问GridFS吗?
I am new to Node.js. Can anyone provide me an example of how to use GridFS for storing and retrieving binary data, such as images, using Node.js and Mongoose? Do I need to directly access GridFS?
推荐答案我对这里评分最高的答案不满意,所以我提供了一个新答案:我最终使用了节点模块 'gridfs-stream'(那里有很棒的文档!)可以通过 npm 安装.有了它,再加上猫鼬,它可能看起来像这样:
I was not satisfied with the highest rated answer here and so I'm providing a new one: I ended up using the node module 'gridfs-stream' (great documentation there!) which can be installed via npm. With it, and in combination with mongoose, it could look like this:
var fs = require('fs'); var mongoose = require("mongoose"); var Grid = require('gridfs-stream'); var GridFS = Grid(mongoose.connection.db, mongoose.mongo); function putFile(path, name, callback) { var writestream = GridFS.createWriteStream({ filename: name }); writestream.on('close', function (file) { callback(null, file); }); fs.createReadStream(path).pipe(writestream); }注意 path 是文件在本地系统上的路径.
Note that path is the path of the file on the local system.
至于我的文件读取功能,就我而言,我只需要将文件流式传输到浏览器(使用 express):
As for my read function of the file, for my case I just need to stream the file to the browser (using express):
try { var readstream = GridFS.createReadStream({_id: id}); readstream.pipe(res); } catch (err) { log.error(err); return next(errors.create(404, "File not found.")); }更多推荐
如何使用 GridFS 使用 Node.js 和 Mongoose 存储图像
发布评论