JBone
JBone

Reputation: 1784

Attaching a stream in response in expresses/nodejs

I am having difficulties sending a stream back in response using ExpressJs. Can someone look into it and help me understand where I am making the mistake in this code?

This is .mp4 file that I am sending back.

Also, I have the requested file that I am trying to read in Mongo Grid as shown below

    { "_id" : ObjectId("5702b22fc327277b338a4229"), "filename" :      **"vsl_video1.mp4"**, "contentType" : "binary/octet-stream", "length" : 29442776, "chunkSize" : 261120, "uploadDate" : ISODate("2016-04-04T18:28:00.324Z"), "aliases" : null, "metadata" : null, "md5" : "33c0daecaf9d6d84408041dfe5724295" }

And here is my code that is trying to read this file and trying to attache it in the response

    filename = req.params.filename;
    MongoClient.connect(mongoUrl, function(err, db) {
      var gridReadStream, gridfs;
      gridfs = Grid(db, Mongo);
      gridReadStream = gridfs.createReadStream({
        filename: filename
      });
      console.log('after creating the read stream');
      console.log(filename);
      gridReadStream.pipe(res);
      db.close();
      return res.status(200);

When I post the request, I am able to print the two console logs. I am sure readstream works fine as well (I tested to write to a local file and it did write binary data to that file), so for some reason, the response is not working.

I don't get any errors to post here. I see that my response never comes back and it times out after a long time.

Any suggestions would be greatly appreciated.

Upvotes: 1

Views: 1687

Answers (1)

christophetd
christophetd

Reputation: 3874

From this answer. Maybe try removing your res.status(200) or doing the following

gridReadStream.on('data', function(data) {
    res.write(data);
});

gridReadStream.on('end', function() {
    res.status(200).end();
});

Not sure at all, tough

Upvotes: 3

Related Questions