0

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..

cauchi
  • 1,463
  • 2
  • 17
  • 45
  • 3
    1. You don't open a database connection in your route logic, but you do it for your application lifecycle. 2. "Callbacks" These things need to happen "after" the database is opened. The `.open()` call is asynchronous. –  Jun 18 '15 at 09:44
  • Yes, I have to move the connection, but I wanted a very simple example to work first. For some reason I had put the actual read from the database outside the callback. Thanks. – cauchi Jun 18 '15 at 10:05

1 Answers1

1

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.

BlackMamba
  • 10,054
  • 7
  • 44
  • 67