• Stars
    star
    615
  • Rank 72,947 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easily stream files to and from MongoDB

gridfs-stream

Easily stream files to and from MongoDB GridFS.

Please note

gridfs-stream v1.x uses Stream2 API from nodejs v0.10 (and the mongodb v2.x driver). It provides more robust and easier to use streams. If for some reason you need nodejs v0.8 streams, please switch to the gridfs-stream 0.x branch

Description

var mongo = require('mongodb');
var Grid = require('gridfs-stream');

// create or use an existing mongodb-native db instance
var db = new mongo.Db('yourDatabaseName', new mongo.Server("127.0.0.1", 27017));
var gfs = Grid(db, mongo);

// streaming to gridfs
var writestream = gfs.createWriteStream({
    filename: 'my_file.txt'
});
fs.createReadStream('/some/path').pipe(writestream);

// streaming from gridfs
var readstream = gfs.createReadStream({
  filename: 'my_file.txt'
});

//error handling, e.g. file does not exist
readstream.on('error', function (err) {
  console.log('An error occurred!', err);
  throw err;
});

readstream.pipe(response);

Alternatively you could read the file using an _id. This is often a better option, since filenames don't have to be unique within the collection. e.g.

var readstream = gfs.createReadStream({
  _id: '50e03d29edfdc00d34000001'
});

Created streams are compatible with other Node streams so piping anywhere is easy.

install

npm install gridfs-stream

use

var mongo = require('mongodb');
var Grid = require('gridfs-stream');

// create or use an existing mongodb-native db instance.
// for this example we'll just create one:
var db = new mongo.Db('yourDatabaseName', new mongo.Server("127.0.0.1", 27017));

// make sure the db instance is open before passing into `Grid`
db.open(function (err) {
  if (err) return handleError(err);
  var gfs = Grid(db, mongo);

  // all set!
})

The gridfs-stream module exports a constructor that accepts an open mongodb-native db and the mongodb-native driver you are using. The db must already be opened before calling createWriteStream or createReadStream.

Now we're ready to start streaming.

createWriteStream

To stream data to GridFS we call createWriteStream passing any options.

var writestream = gfs.createWriteStream([options]);
fs.createReadStream('/some/path').pipe(writestream);

Options may contain zero or more of the following options, for more information see GridStore:

{
    _id: '50e03d29edfdc00d34000001', // a MongoDb ObjectId
    filename: 'my_file.txt', // a filename
    mode: 'w', // default value: w

    //any other options from the GridStore may be passed too, e.g.:

    chunkSize: 1024,
    content_type: 'plain/text', // For content_type to work properly, set "mode"-option to "w" too!
    root: 'my_collection',
    metadata: {
        ...
    }
}

Events

The writeStream is a fully compliant Stream2 Writable Stream, it emits all the associated events (drain, finish, pipe, unpipe, error), as well as additional special events (open, close).

finish is emitted after the file has been completely written to GridFS.

open is emitted after the GridStore is successfully opened.

close is emitted after the GridStore is successfully closed, which means the file is fully written to GridFS, and the file object is passed as the first argument.

writestream.on('close', function (file) {
  // do something with `file`
  console.log(file.filename);
});

Methods

The writeStream has additional methods:

destroy([err]): Destroy the writeStream as soon as possible: stop writing incoming data, close the _store. An error event will be emitted, as well as a close event. It's up to you to cleanup the GridStore if it's not desired to keep half written files in GridFS (the close event returns a GridStore file which can be used to delete the file, or mark it failed).

createReadStream

To stream data out of GridFS we call createReadStream passing any options, at least an _id or filename.

var readstream = gfs.createReadStream(options);
readstream.pipe(response);

See the options of createWriteStream for more information.

To get partial data with createReadStream, use range option. e.g.

var readstream = gfs.createReadStream({
  _id: '50e03d29edfdc00d34000001',
  range: {
    startPos: 100,
    endPos: 500000
  }
});

removing files

Files can be removed by passing options (at least an _id or filename) to the remove() method.

gfs.remove(options, function (err, gridStore) {
  if (err) return handleError(err);
  console.log('success');
});

See the options of createWriteStream for more information.

check if file exists

Check if a file exist by passing options (at least an _id or filename) to the exist() method.

gfs.exist(options, function (err, found) {
  if (err) return handleError(err);
  found ? console.log('File exists') : console.log('File does not exist');
});

See the options of createWriteStream for more information.

accessing file metadata

All file meta-data (file name, upload date, contentType, etc) are stored in a special mongodb collection separate from the actual file data. This collection can be queried directly:

  var gfs = Grid(conn.db);
  gfs.files.find({ filename: 'myImage.png' }).toArray(function (err, files) {
    if (err) ...
    console.log(files);
  })

Alternatively you can use the gfs.findOne-shorthand to find a single file

  gfs.findOne({ _id: '54da7b013706c1e7ab25f9fa'}, function (err, file) {
    console.log(file);
  });

using with mongoose

var mongoose = require('mongoose');
var Grid = require('gridfs-stream');

var conn = mongoose.createConnection(..);
conn.once('open', function () {
  var gfs = Grid(conn.db, mongoose.mongo);

  // all set!
})

You may optionally assign the driver directly to the gridfs-stream module so you don't need to pass it along each time you construct a grid:

var mongoose = require('mongoose');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;

var conn = mongoose.createConnection(..);
conn.once('open', function () {
  var gfs = Grid(conn.db);

  // all set!
})

LICENSE

More Repositories

1

gm

GraphicsMagick for node
JavaScript
6,950
star
2

m

mongodb version management
Shell
267
star
3

node-ses

DEPRECATED
JavaScript
200
star
4

observed

ES6 Object.observe with nested object support - the way I want it (DEPRECATED)
JavaScript
159
star
5

sliced

A faster JavaScript alternative to [].slice.call(arguments)
JavaScript
95
star
6

mpromise

Promises/A+ conformant implementation
JavaScript
86
star
7

node-email

DEPRECATED
JavaScript
84
star
8

greadme

Locally preview your markdown, Github style
JavaScript
76
star
9

gleak

Global variable leak detection for Node.js
JavaScript
70
star
10

gridform

Stream formidable uploads into MongoDB GridFS
JavaScript
59
star
11

muri

Muri is your friendly neighborhood MongoDB URI parser for Node.js
JavaScript
32
star
12

jquery.hook

Enables hooking into any jQuery method
31
star
13

js-styleguide

A javascript style guide.
27
star
14

mongooser

Mongoose REPL
JavaScript
23
star
15

connect-multipart-gridform

Connect multipart middleware configured to use MongoDB GridFS for file storage.
JavaScript
18
star
16

gm-demo

image manipulation demo on heroku
JavaScript
16
star
17

Nodal-Kombat

Multiplayer realtime fighting game
JavaScript
16
star
18

koa-mongodb-session

MongoDB backed session middleware for koa.js
JavaScript
15
star
19

graceful-shutdown

Shuts down a server gracefully upon the first specified signal received
JavaScript
13
star
20

mongodb-schema-miner

Generate schemata from MongoDB collections
JavaScript
12
star
21

jQuery.use

jQuery.use provides you on demand asynchronously loaded jQuery plugins at your fingertips.
JavaScript
11
star
22

regexp-clone

Clones RegExps with flag and lastIndex preservation
JavaScript
9
star
23

channel9

channel9 demo of nodejs + mongodb + graphicsmagick
JavaScript
8
star
24

gomon

MongoDB shell written in Node.js
JavaScript
8
star
25

.vim

vim
Vim Script
8
star
26

koa-session-mongodb

MongoDB backed session middleware for Koa
JavaScript
8
star
27

mongorc.js

.mongorc.js helpers
JavaScript
8
star
28

node-gameroom

My basic starter kit for creating realtime web-based games with nodejs.
JavaScript
8
star
29

once-upon

Executes a callback at most once upon the first of any number of events
JavaScript
7
star
30

express-custom-errors

What if you want to serve customized views for 403, 502, etc? That's what this plugin is for.
JavaScript
3
star
31

jquery-ui-lasso

A simple mouse lasso for jQuery ui
3
star
32

npm-downloads

Prints the number of downloads for a given npm package and the packages that directly depend on it
JavaScript
3
star
33

mongo-replset-test

Quickly set up a mongodb replica set test with authentication enabled
JavaScript
3
star
34

groups-of

Divides arrays into groups of a specified cardinality.
JavaScript
2
star
35

node-gmp

gmp for node
JavaScript
2
star
36

tic-tac-node

A silly demo of node and express
JavaScript
1
star
37

nproj

bare bones node project generator
Shell
1
star
38

talks

My talks
JavaScript
1
star
39

workshop-04-2013

JavaScript
1
star
40

npm-update-test

Test repo for https://github.com/npm/npm/issues/19107
1
star