Download of GridFs using nodejs does not start

184 views Asked by At

I'm trying to download a binary file of +200M saved in a mongoDB using the GridFS. My problem is that the download won't start. I'm using nodejs with mongodb and gridfs-stream.

In 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');
});

Somewhere in my view:

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

which generates a response from the nodejs log:

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

but the download never starts... and I have no idea what's going on..

1

There are 1 answers

1
BlackMamba On BEST ANSWER

change

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);

to

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);
        });

Please try.