【问题标题】:Download of GridFs using nodejs does not start使用 nodejs 下载 GridFs 无法启动
【发布时间】:2015-06-18 09:39:14
【问题描述】:

我正在尝试使用 GridFS 下载保存在 mongoDB 中的 +200M 二进制文件。我的问题是无法开始下载。我正在使用带有 mongodb 和 gridfs-stream 的 nodejs。

在 routes.js 中:

router.get('/getlog',function(req,res) {
    if (req.isAuthenticated())
    {
        var mongo = require('mongodb');
        var Grid = require('gridfs-stream');
        var db = new mongo.Db('logApp', new mongo.Server("127.0.0.1", 27017));

        db.open(function (err) {
            if (err) 
                return handleError(err);
        });

        var gfs = Grid(db, mongo);
        var id = req.query.id;
        gfs.exist({_id: id}, function (err, found) {
            if (err) return handleError(err);
            if (!found)
                res.send('Error on the database looking for the file.')
        });

        var readStream = gfs.createReadStream({
            _id: id
        }).pipe(res);
    }
    else
        res.redirect('/login');
});

在我看来:

td #[a(href="getlog?id=#{log.logId}", download="logfile") #[span(name='log').glyphicon.glyphicon-download]]

从 nodejs 日志生成响应:

GET /getlog?id=55818770b276172922b945b8 - - ms - -

但下载永远不会开始......我不知道发生了什么......

【问题讨论】:

  • 1.您不会在路由逻辑中打开数据库连接,而是在应用程序生命周期中这样做。 2.“回调”这些事情需要在数据库打开“之后”发生。 .open() 调用是异步的。
  • 是的,我必须移动连接,但我想要一个非常简单的示例来首先工作。出于某种原因,我将数据库中的实际读取放在回调之外。谢谢。

标签: node.js mongodb gridfs gridfs-stream


【解决方案1】:

改变

gfs.exist({_id: id}, function (err, found) {
            if (err) return handleError(err);
            if (!found)
                res.send('Error on the database looking for the file.')
        });

        var readStream = gfs.createReadStream({
            _id: id
        }).pipe(res);

gfs.exist({_id: id}, function (err, found) {
            if (err) return handleError(err);
            if (!found)
                return res.send('Error on the database looking for the file.');
            gfs.createReadStream({_id: id}).pipe(res);
        });

请尝试。

【讨论】:

  • 是的。我只是想通了,找到了你的答案。我把调用放在回调之外。
猜你喜欢
  • 2012-11-10
  • 2014-04-19
  • 2016-01-07
  • 2017-04-10
  • 1970-01-01
  • 2018-10-30
  • 2015-07-18
  • 2014-11-25
  • 2021-06-21
相关资源
最近更新 更多