SecStone
SecStone

Reputation: 1753

Store Stream in GridFS using Node.js

I'd like to store a Stream in a GridFS. However it doesn't work as expected (i.e. no console log).

var mongo = require("mongodb");

var db = ...

db.open(function (err, db) {
    var stream = ...
    var name = 'foobar';

    var gs = new mongo.GridStore(db, new mongo.ObjectID, name, "w");
    gs.open(function (err, gs) {
        stream.on("data", function (data) {
            gs.write(data, function (err, gs) {
                if (err) {
                    // ...
                }
            });
        });
        stream.on("end", function () {
            gs.close(function (err, gs) {
                if (!err) {
                    console.log(name + " has been stored to database.");
                }
            });
        });
    });
});

Does anyone know why it doesn't work?

Upvotes: 0

Views: 283

Answers (1)

bennidi
bennidi

Reputation: 2122

I think you forgot to pipe the stream into the gridfs file. You can do it directly since a gridfs file behaves like a stream (see the last line within the db.open callback). Also you forgot the parenthesis on constructor invocation of ObjectID and you don't check for any errors when opening either db or file. My code looks structurally equal and it does work. Hope that helps...

db.open(function (err, db) {
    var stream = ...
    var name = 'foobar';

    var gs = new mongo.GridStore(db, new mongo.ObjectID(), name, "w");
    gs.open(function (err, gs) {
            if(err) console.log(...)
            else{
        stream.on("data", function (data) {
            gs.write(data, function (err, gs) {
                if (err) {
                    // ...
                }
            });
        });
        stream.on("end", function () {
            gs.close(function (err, gs) {
                if (!err) {
                    console.log(name + " has been stored to database.");
                }
            });
        });
           stream.pipe(gs);
          }
    });
});

Upvotes: 1

Related Questions