Class: GridStore

GridStore

new GridStore(db, id, filename, mode, options){GridStore}

Create a new GridStore instance

Modes

  • "r" - read only. This is the default mode.
  • "w" - write in truncate mode. Existing data will be overwriten.
Name Type Default Description
db Db

A database instance to interact with.

id object optional

optional unique id for this file

filename string optional

optional filename for this file, no unique constrain on the field

mode string

set the mode for this file.

options object null optional

Optional settings.

Name Type Default Description
w number | string null optional

The write concern.

wtimeout number null optional

The write concern timeout.

j boolean false optional

Specify a journal write concern.

fsync boolean false optional

Specify a file sync write concern.

root string null optional

Root collection to use. Defaults to {GridStore.DEFAULT_ROOT_COLLECTION}.

content_type string null optional

MIME type of the file. Defaults to {GridStore.DEFAULT_CONTENT_TYPE}.

chunk_size number 261120 optional

Size for the chunk. Defaults to {Chunk.DEFAULT_CHUNK_SIZE}.

metadata object null optional

Arbitrary data the user wants to store.

promiseLibrary object null optional

A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible

readPreference ReadPreference | string null optional

The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

Properties:
Name Type Description
chunkSize number

Get the gridstore chunk size.

md5 number

The md5 checksum for this file.

chunkNumber number

The current chunk number the gridstore has materialized into memory

Returns:
GridStore instance.

Members

staticGridStore.DEFAULT_CONTENT_TYPE

Default file mime type

staticGridStore.DEFAULT_ROOT_COLLECTION

The collection to be used for holding the files and chunks collection.

staticGridStore.IO_SEEK_CUR

Seek mode where the given length is an offset to the current read/write head.

staticGridStore.IO_SEEK_END

Seek mode where the given length is an offset to the end of the file.

staticGridStore.IO_SEEK_SET

Seek mode where the given length is absolute.

Methods

staticGridStore.exist(db, name, rootCollection, options, callback){Promise}

Checks if a file exists in the database.

Name Type Default Description
db Db

the database to query.

name string

The name of the file to look for.

rootCollection string optional

The root collection that holds the files and chunks collection. Defaults to {GridStore.DEFAULT_ROOT_COLLECTION}.

options object null optional

Optional settings.

Name Type Default Description
readPreference ReadPreference | string null optional

The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

promiseLibrary object null optional

A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible

callback GridStore~resultCallback optional

result from exists.

Returns:
Promise if no callback passed

staticGridStore.list(db, rootCollection, options, callback){Promise}

Gets the list of files stored in the GridFS.

Name Type Default Description
db Db

the database to query.

rootCollection string optional

The root collection that holds the files and chunks collection. Defaults to {GridStore.DEFAULT_ROOT_COLLECTION}.

options object null optional

Optional settings.

Name Type Default Description
readPreference ReadPreference | string null optional

The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

promiseLibrary object null optional

A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible

callback GridStore~resultCallback optional

result from exists.

Returns:
Promise if no callback passed

staticGridStore.read(db, name, length, offset, options, callback){Promise}

Reads the contents of a file.

This method has the following signatures

(db, name, callback)
(db, name, length, callback)
(db, name, length, offset, callback)
(db, name, length, offset, options, callback)

Name Type Default Description
db Db

the database to query.

name string

The name of the file.

length number optional

The size of data to read.

offset number optional

The offset from the head of the file of which to start reading from.

options object null optional

Optional settings.

Name Type Default Description
readPreference ReadPreference | string null optional

The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

promiseLibrary object null optional

A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible

callback GridStore~readCallback optional

the command callback.

Returns:
Promise if no callback passed

staticGridStore.readlines(db, name, separator, options, callback){Promise}

Read the entire file as a list of strings splitting by the provided separator.

Name Type Default Description
db Db

the database to query.

name String | object

the name of the file.

separator string optional

The character to be recognized as the newline separator.

options object null optional

Optional settings.

Name Type Default Description
readPreference ReadPreference | string null optional

The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).

promiseLibrary object null optional

A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible

callback GridStore~readlinesCallback optional

the command callback.

Returns:
Promise if no callback passed

Deletes the chunks and metadata information of a file from GridFS.

Name Type Default Description
db Db

The database to query.

names string | array

The name/names of the files to delete.

options object null optional

Optional settings.

Name Type Default Description
promiseLibrary object null optional

A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible

callback GridStore~resultCallback optional

the command callback.

Returns:
Promise if no callback passed

chunkCollection(callback){Collection}

Retrieve this file's chunks collection.

Name Type Description
callback GridStore~collectionCallback

the command callback.

Example
// A simple example showing how to access the chunks collection object.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  gridStore.open(function(err, gridStore) {

    // Access the Chunk collection
    gridStore.chunkCollection(function(err, collection) {
      test.equal(err, null);

      db.close();
    });
  });
});

close(callback){Promise}

Saves this file to the database. This will overwrite the old entry if it
already exists. This will work properly only if mode was initialized to
"w" or "w+".

Name Type Description
callback GridStore~resultCallback optional

this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.

Returns:
Promise if no callback passed
Examples
// A simple example showing how to use the write command with strings and Buffers.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  gridStore.open(function(err, gridStore) {

    // Write a text string
    gridStore.write('Hello world', function(err, gridStore) {

      // Close the
      gridStore.close(function(err, result) {
        test.equal(err, null);

        db.close();
      });
    });
  });
});
// A simple example showing how to use the write command with strings and Buffers using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  gridStore.open().then(function(gridStore) {

    // Write a text string
    gridStore.write('Hello world').then(function(gridStore) {

      // Close the
      gridStore.close().then(function(result) {

        db.close();
      });
    });
  });
});
// A simple example showing how to use the write command with strings and Buffers using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  yield gridStore.open();

  // Write a text string
  yield gridStore.write('Hello world');

  // Close the
  yield gridStore.close();

  db.close();
});

Retrieves the file collection associated with this object.

Name Type Description
callback GridStore~collectionCallback

the command callback.

Example
// A simple example showing how to access the files collection object.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  gridStore.open(function(err, gridStore) {

    // Access the Chunk collection
    gridStore.collection(function(err, collection) {
      test.equal(err, null);

      db.close();
    });
  });
});

Handles the destroy part of a stream

Verify if the file is at EOF.

Returns:
if the read/write head is at the end of this file.
Example
// A simple example showing the usage of the eof method.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

  // Open the file in write mode
  var gridStore = new GridStore(db, 'test_gs_empty_file_eof', "w");
  gridStore.open(function(err, gridStore) {
    // Flush the empty file to GridFS
    gridStore.close(function(err, gridStore) {

      // Open the file in read mode
      var gridStore2 = new GridStore(db, 'test_gs_empty_file_eof', "r");
      gridStore2.open(function(err, gridStore) {
        // Verify that we are at the end of the file
        test.equal(true, gridStore.eof());

        db.close();
      })
    });
  });
});

getc(callback){Promise}

Retrieves a single character from this file.

Name Type Description
callback GridStore~resultCallback optional

this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file.

Returns:
Promise if no callback passed
Examples
// A simple example showing the usage of the seek method.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create a file and open it
  var gridStore = new GridStore(db, "test_gs_getc_file", "w");
  gridStore.open(function(err, gridStore) {
    // Write some content to the file
    gridStore.write(new Buffer("hello, world!", "utf8"), function(err, gridStore) {
      // Flush the file to GridFS
      gridStore.close(function(result) {

        // Open the file in read mode
        var gridStore2 = new GridStore(db, "test_gs_getc_file", "r");
        gridStore2.open(function(err, gridStore) {

          // Read first character and verify
          gridStore.getc(function(err, chr) {
            test.equal('h', chr);

            db.close();
          });
        });
      });
    });
  });
});
// A simple example showing the usage of the seek method using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create a file and open it
  var gridStore = new GridStore(db, "test_gs_getc_file", "w");
  gridStore.open().then(function(gridStore) {
    // Write some content to the file
    gridStore.write(new Buffer("hello, world!", "utf8")).then(function(gridStore) {
      // Flush the file to GridFS
      gridStore.close().then(function(result) {

        // Open the file in read mode
        var gridStore2 = new GridStore(db, "test_gs_getc_file", "r");
        gridStore2.open().then(function(gridStore) {

          // Read first character and verify
          gridStore.getc().then(function(chr) {
            test.equal('h', chr);

            db.close();
          });
        });
      });
    });
  });
});
// A simple example showing the usage of the seek method using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Create a file and open it
  var gridStore = new GridStore(db, "test_gs_getc_file", "w");
  yield gridStore.open();
  // Write some content to the file
  yield gridStore.write(new Buffer("hello, world!", "utf8"));
  // Flush the file to GridFS
  yield gridStore.close();
  // Open the file in read mode
  var gridStore = new GridStore(db, "test_gs_getc_file", "r");
  yield gridStore.open();

  // Read first character and verify
  var chr = yield gridStore.getc();
  test.equal('h', chr);

  db.close();
});

open(callback){Promise}

Opens the file from the database and initialize this object. Also creates a
new one if file does not exist.

Name Type Description
callback GridStore~openCallback optional

this will be called after executing this method

Returns:
Promise if no callback passed
Examples
// A simple example showing opening a file using a filename, writing to it and saving it.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create a new instance of the gridstore
  var gridStore = new GridStore(db, 'ourexamplefiletowrite.txt', 'w');

  // Open the file
  gridStore.open(function(err, gridStore) {

    // Write some data to the file
    gridStore.write('bar', function(err, gridStore) {
      test.equal(null, err);

      // Close (Flushes the data to MongoDB)
      gridStore.close(function(err, result) {
        test.equal(null, err);

        // Verify that the file exists
        GridStore.exist(db, 'ourexamplefiletowrite.txt', function(err, result) {
          test.equal(null, err);
          test.equal(true, result);

          db.close();
        });
      });
    });
  });
});
// A simple example showing opening a file using an ObjectID, writing to it and saving it.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Create a new instance of the gridstore
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the file
  gridStore.open(function(err, gridStore) {

    // Write some data to the file
    gridStore.write('bar', function(err, gridStore) {
      test.equal(null, err);

      // Close (Flushes the data to MongoDB)
      gridStore.close(function(err, result) {
        test.equal(null, err);

        // Verify that the file exists
        GridStore.exist(db, fileId, function(err, result) {
          test.equal(null, err);
          test.equal(true, result);

          db.close();
        });
      });
    });
  });
});
// A simple example showing how to save a file with a filename allowing for multiple files with the same name

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create a file and open it
  var gridStore = new GridStore(db, new ObjectID(), "test_gs_getc_file", "w");
  gridStore.open(function(err, gridStore) {
    // Write some content to the file
    gridStore.write(new Buffer("hello, world!", "utf8"), function(err, gridStore) {
      // Flush the file to GridFS
      gridStore.close(function(err, fileData) {
        test.equal(null, err);

        // Create another file with same name and and save content to it
        gridStore = new GridStore(db, new ObjectID(), "test_gs_getc_file", "w");
        gridStore.open(function(err, gridStore) {
          // Write some content to the file
          gridStore.write(new Buffer("hello, world!", "utf8"), function(err, gridStore) {
            // Flush the file to GridFS
            gridStore.close(function(err, fileData) {
              test.equal(null, err);

              // Open the file in read mode using the filename
              var gridStore2 = new GridStore(db, "test_gs_getc_file", "r");
              gridStore2.open(function(err, gridStore) {

                // Read first character and verify
                gridStore.getc(function(err, chr) {
                  test.equal('h', chr);

                  // Open the file using an object id
                  gridStore2 = new GridStore(db, fileData._id, "r");
                  gridStore2.open(function(err, gridStore) {

                    // Read first character and verify
                    gridStore.getc(function(err, chr) {
                      test.equal('h', chr);

                      db.close();
                    })
                  });
                });
              });
            });
          });
        });
      });
    });
  });
});
// A simple example showing opening a file using a filename, writing to it and saving it using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create a new instance of the gridstore
  var gridStore = new GridStore(db, 'ourexamplefiletowrite.txt', 'w');

  // Open the file
  gridStore.open().then(function(gridStore) {

    // Write some data to the file
    gridStore.write('bar').then(function(gridStore) {

      // Close (Flushes the data to MongoDB)
      gridStore.close().then(function(result) {

        // Verify that the file exists
        GridStore.exist(db, 'ourexamplefiletowrite.txt').then(function(result) {
          test.equal(true, result);

          db.close();
        });
      });
    });
  });
});
// A simple example showing opening a file using an ObjectID, writing to it and saving it using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Create a new instance of the gridstore
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the file
  gridStore.open().then(function(gridStore) {

    // Write some data to the file
    gridStore.write('bar').then(function(gridStore) {

      // Close (Flushes the data to MongoDB)
      gridStore.close().then(function(result) {

        // Verify that the file exists
        GridStore.exist(db, fileId).then(function(result) {
          test.equal(true, result);

          db.close();
        });
      });
    });
  });
});
// A simple example showing how to save a file with a filename allowing for multiple files with the same name using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create a file and open it
  var gridStore = new GridStore(db, new ObjectID(), "test_gs_getc_file", "w");
  gridStore.open().then(function(gridStore) {
    // Write some content to the file
    gridStore.write(new Buffer("hello, world!", "utf8")).then(function(gridStore) {
      // Flush the file to GridFS
      gridStore.close().then(function(fileData) {

        // Create another file with same name and and save content to it
        gridStore = new GridStore(db, new ObjectID(), "test_gs_getc_file", "w");
        gridStore.open().then(function(gridStore) {
          // Write some content to the file
          gridStore.write(new Buffer("hello, world!", "utf8")).then(function(gridStore) {
            // Flush the file to GridFS
            gridStore.close().then(function(fileData) {

              // Open the file in read mode using the filename
              var gridStore2 = new GridStore(db, "test_gs_getc_file", "r");
              gridStore2.open().then(function(gridStore) {

                // Read first character and verify
                gridStore.getc().then(function(chr) {
                  test.equal('h', chr);

                  // Open the file using an object id
                  gridStore2 = new GridStore(db, fileData._id, "r");
                  gridStore2.open().then(function(gridStore) {

                    // Read first character and verify
                    gridStore.getc().then(function(chr) {
                      test.equal('h', chr);

                      db.close();
                    })
                  });
                });
              });
            });
          });
        });
      });
    });
  });
});
// A simple example showing opening a file using a filename, writing to it and saving it using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Create a new instance of the gridstore
  var gridStore = new GridStore(db, 'ourexamplefiletowrite.txt', 'w');

  // Open the file
  yield gridStore.open();

  // Write some data to the file
  yield gridStore.write('bar');

  // Close (Flushes the data to MongoDB)
  yield gridStore.close();

  // Verify that the file exists
  var result = yield GridStore.exist(db, 'ourexamplefiletowrite.txt');
  test.equal(true, result);

  db.close();
});
// A simple example showing opening a file using an ObjectID, writing to it and saving it using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Our file ID
  var fileId = new ObjectID();

  // Create a new instance of the gridstore
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the file
  yield gridStore.open();

  // Write some data to the file
  yield gridStore.write('bar');

  // Close (Flushes the data to MongoDB)
  yield gridStore.close();

  // Verify that the file exists
  var result = yield GridStore.exist(db, fileId);
  test.equal(true, result);

  db.close();
});
// A simple example showing how to save a file with a filename allowing for multiple files with the same name using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Create a file and open it
  var gridStore = new GridStore(db, new ObjectID(), "test_gs_getc_file", "w");
  yield gridStore.open();
  // Write some content to the file
  yield gridStore.write(new Buffer("hello, world!", "utf8"));
  // Flush the file to GridFS
  yield gridStore.close();

  // Create another file with same name and and save content to it
  gridStore = new GridStore(db, new ObjectID(), "test_gs_getc_file", "w");
  yield gridStore.open();
  // Write some content to the file
  yield gridStore.write(new Buffer("hello, world!", "utf8"));
  // Flush the file to GridFS
  var fileData = yield gridStore.close();

  // Open the file in read mode using the filename
  var gridStore = new GridStore(db, "test_gs_getc_file", "r");
  yield gridStore.open();

  // Read first character and verify
  var chr = yield gridStore.getc();
  test.equal('h', chr);

  // Open the file using an object id
  gridStore = new GridStore(db, fileData._id, "r");
  yield gridStore.open();

  // Read first character and verify
  var chr = yield gridStore.getc();
  test.equal('h', chr);

  db.close();
});

puts(string, callback){Promise}

Writes a string to the file with a newline character appended at the end if
the given string does not have one.

Name Type Description
string string

the string to write.

callback GridStore~resultCallback optional

this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.

Returns:
Promise if no callback passed
Examples
// A simple example showing the usage of the puts method.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Open a file for writing
  var gridStore = new GridStore(db, "test_gs_puts_and_readlines", "w");
  gridStore.open(function(err, gridStore) {

    // Write a line to the file using the puts method
    gridStore.puts("line one", function(err, gridStore) {

      // Flush the file to GridFS
      gridStore.close(function(err, result) {

        // Read in the entire contents
        GridStore.read(db, 'test_gs_puts_and_readlines', function(err, data) {
          test.equal("line one\n", data.toString());

          db.close();
        });
      });
    });
  });
});
// A simple example showing the usage of the puts method using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Open a file for writing
  var gridStore = new GridStore(db, "test_gs_puts_and_readlines", "w");
  gridStore.open().then(function(gridStore) {

    // Write a line to the file using the puts method
    gridStore.puts("line one").then(function(gridStore) {

      // Flush the file to GridFS
      gridStore.close().then(function(result) {

        // Read in the entire contents
        GridStore.read(db, 'test_gs_puts_and_readlines').then(function(data) {
          test.equal("line one\n", data.toString());

          db.close();
        });
      });
    });
  });
});
// A simple example showing the usage of the puts method using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Open a file for writing
  var gridStore = new GridStore(db, "test_gs_puts_and_readlines", "w");
  yield gridStore.open();

  // Write a line to the file using the puts method
  yield gridStore.puts("line one");

  // Flush the file to GridFS
  yield gridStore.close();

  // Read in the entire contents
  var data = yield GridStore.read(db, 'test_gs_puts_and_readlines');
  test.equal("line one\n", data.toString());

  db.close();
});

read(length, buffer, callback){Promise}

Retrieves the contents of this file and advances the read/write head. Works with Buffers only.

There are 3 signatures for this method:

(callback)
(length, callback)
(length, buffer, callback)

Name Type Description
length number optional

the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified.

buffer string | Buffer optional

a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method.

callback GridStore~readCallback optional

the command callback.

Returns:
Promise if no callback passed
Examples
// A simple example showing the usage of the read method.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Read in the content of a file
  var data = fs.readFileSync('./test/functional/data/iya_logo_final_bw.jpg');
  // Create a new file
  var gs = new GridStore(db, "test", "w");
  // Open the file
  gs.open(function(err, gs) {
    // Write the file to GridFS
    gs.write(data, function(err, gs) {
      // Flush to the GridFS
      gs.close(function(err, gs) {

        // Define the file we wish to read
        var gs2 = new GridStore(db, "test", "r");
        // Open the file
        gs2.open(function(err, gs) {
          // Set the pointer of the read head to the start of the gridstored file
          gs2.seek(0, function() {
            // Read the entire file
            gs2.read(function(err, data2) {
              // Compare the file content against the orgiinal
              test.equal(data.toString('base64'), data2.toString('base64'));

              db.close();
            });
          });
        });
      });
    });
  });
});
// A simple example showing the usage of the read method using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Read in the content of a file
  var data = fs.readFileSync('./test/functional/data/iya_logo_final_bw.jpg');
  // Create a new file
  var gs = new GridStore(db, "test", "w");
  // Open the file
  gs.open().then(function(gs) {
    // Write the file to GridFS
    gs.write(data).then(function(gs) {
      // Flush to the GridFS
      gs.close().then(function(gs) {

        // Define the file we wish to read
        var gs2 = new GridStore(db, "test", "r");
        // Open the file
        gs2.open().then(function(gs) {
          // Set the pointer of the read head to the start of the gridstored file
          gs2.seek(0).then(function() {
            // Read the entire file
            gs2.read().then(function(data2) {
              // Compare the file content against the orgiinal
              test.equal(data.toString('base64'), data2.toString('base64'));

              db.close();
            });
          });
        });
      });
    });
  });
});
// A simple example showing the usage of the read method using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Read in the content of a file
  var data = fs.readFileSync('./test/functional/data/iya_logo_final_bw.jpg');
  // Create a new file
  var gs = new GridStore(db, "test", "w");
  // Open the file
  yield gs.open();
  // Write the file to GridFS
  yield gs.write(data);
  // Flush to the GridFS
  yield gs.close();

  // Define the file we wish to read
  var gs2 = new GridStore(db, "test", "r");
  // Open the file
  yield gs2.open();
  // Set the pointer of the read head to the start of the gridstored file
  yield gs2.seek(0);
  // Read the entire file
  var data2 = yield gs2.read();
  // Compare the file content against the orgiinal
  test.equal(data.toString('base64'), data2.toString('base64'));

  db.close();
});

readlines(separator, callback){Promise}

Read the entire file as a list of strings splitting by the provided separator.

Name Type Description
separator string optional

The character to be recognized as the newline separator.

callback GridStore~readlinesCallback optional

the command callback.

Returns:
Promise if no callback passed
Examples
// A simple example showing reading back using readlines to split the text into lines by the seperator provided.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  gridStore.open(function(err, gridStore) {

    // Write one line to gridStore
    gridStore.puts("line one", function(err, gridStore) {

      // Write second line to gridStore
      gridStore.puts("line two", function(err, gridStore) {

        // Write third line to gridStore
        gridStore.puts("line three", function(err, gridStore) {

          // Flush file to disk
          gridStore.close(function(err, result) {

            // Open file for reading
            gridStore = new GridStore(db, fileId, 'r');
            gridStore.open(function(err, gridStore) {

              // Read all the lines and verify correctness
              gridStore.readlines(function(err, lines) {
                test.deepEqual(["line one\n", "line two\n", "line three\n"], lines);

                db.close();
              });
            });
          });
        });
      });
    });
  });
});
// A simple example showing reading back using readlines to split the text into lines by the separator provided using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  gridStore.open().then(function(gridStore) {

    // Write one line to gridStore
    gridStore.puts("line one").then(function(gridStore) {

      // Write second line to gridStore
      gridStore.puts("line two").then(function(gridStore) {

        // Write third line to gridStore
        gridStore.puts("line three").then(function(gridStore) {

          // Flush file to disk
          gridStore.close().then(function(result) {

            // Open file for reading
            gridStore = new GridStore(db, fileId, 'r');
            gridStore.open().then(function(gridStore) {

              // Read all the lines and verify correctness
              gridStore.readlines().then(function(lines) {
                test.deepEqual(["line one\n", "line two\n", "line three\n"], lines);

                db.close();
              });
            });
          });
        });
      });
    });
  });
});
// A simple example showing reading back using readlines to split the text into lines by the separator provided using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  yield gridStore.open();

  // Write one line to gridStore
  yield gridStore.puts("line one");

  // Write second line to gridStore
  yield gridStore.puts("line two");

  // Write third line to gridStore
  yield gridStore.puts("line three");

  // Flush file to disk
  yield gridStore.close();

  // Open file for reading
  gridStore = new GridStore(db, fileId, 'r');
  yield gridStore.open();

  // Read all the lines and verify correctness
  var lines = yield gridStore.readlines();
  test.deepEqual(["line one\n", "line two\n", "line three\n"], lines);

  db.close();
});

rewind(callback){Promise}

Deletes all the chunks of this file in the database if mode was set to "w" or
"w+" and resets the read/write head to the initial position.

Name Type Description
callback GridStore~resultCallback optional

this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.

Returns:
Promise if no callback passed
Examples
// A simple example showing how to rewind and overwrite the file.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Create a new file
  var gridStore = new GridStore(db, fileId, "w");
  // Open the file
  gridStore.open(function(err, gridStore) {
    // Write to the file
    gridStore.write("hello, world!", function(err, gridStore) {
      // Flush the file to disk
      gridStore.close(function(err, result) {

        // Reopen the file
        gridStore = new GridStore(db, fileId, "w");
        gridStore.open(function(err, gridStore) {
          // Write some more text to the file
          gridStore.write('some text is inserted here', function(err, gridStore) {

            // Let's rewind to truncate the file
            gridStore.rewind(function(err, gridStore) {

              // Write something from the start
              gridStore.write('abc', function(err, gridStore) {

                // Flush the data to mongodb
                gridStore.close(function(err, result) {

                  // Verify that the new data was written
                  GridStore.read(db, fileId, function(err, data) {
                    test.equal("abc", data);

                    db.close();
                  });
                });
              });
            });
          });
        });
      });
    });
  });
});
// A simple example showing how to rewind and overwrite the file using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Create a new file
  var gridStore = new GridStore(db, fileId, "w");
  // Open the file
  gridStore.open().then(function(gridStore) {
    // Write to the file
    gridStore.write("hello, world!").then(function(gridStore) {
      // Flush the file to disk
      gridStore.close().then(function(result) {

        // Reopen the file
        gridStore = new GridStore(db, fileId, "w");
        gridStore.open().then(function(gridStore) {
          // Write some more text to the file
          gridStore.write('some text is inserted here').then(function(gridStore) {

            // Let's rewind to truncate the file
            gridStore.rewind().then(function(gridStore) {

              // Write something from the start
              gridStore.write('abc').then(function(gridStore) {

                // Flush the data to mongodb
                gridStore.close().then(function(result) {

                  // Verify that the new data was written
                  GridStore.read(db, fileId).then(function(data) {
                    test.equal("abc", data);

                    db.close();
                  });
                });
              });
            });
          });
        });
      });
    });
  });
});
// A simple example showing how to rewind and overwrite the file using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Our file ID
  var fileId = new ObjectID();

  // Create a new file
  var gridStore = new GridStore(db, fileId, "w");
  // Open the file
  yield gridStore.open();
  // Write to the file
  yield gridStore.write("hello, world!");
  // Flush the file to disk
  yield gridStore.close();

  // Reopen the file
  gridStore = new GridStore(db, fileId, "w");
  yield gridStore.open();
  // Write some more text to the file
  yield gridStore.write('some text is inserted here');

  // Let's rewind to truncate the file
  yield gridStore.rewind();

  // Write something from the start
  yield gridStore.write('abc');

  // Flush the data to mongodb
  yield gridStore.close();

  // Verify that the new data was written
  var data = yield GridStore.read(db, fileId);
  test.equal("abc", data);

  db.close();
});

seek(position, seekLocation, callback){Promise}

Moves the read/write head to a new location.

There are 3 signatures for this method

Seek Location Modes

  • GridStore.IO_SEEK_SET, (default) set the position from the start of the file.
  • GridStore.IO_SEEK_CUR, set the position from the current position in the file.
  • GridStore.IO_SEEK_END, set the position from the end of the file.
Name Type Description
position number optional

the position to seek to

seekLocation number optional

seek mode. Use one of the Seek Location modes.

callback GridStore~gridStoreCallback optional

the command callback.

Returns:
Promise if no callback passed
Example
// A simple example showing the usage of the seek method.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create a file and open it
  var gridStore = new GridStore(db, "test_gs_seek_with_buffer", "w");
  gridStore.open(function(err, gridStore) {
    // Write some content to the file
    gridStore.write(new Buffer("hello, world!", "utf8"), function(err, gridStore) {
      // Flush the file to GridFS
      gridStore.close(function(result) {

        // Open the file in read mode
        var gridStore2 = new GridStore(db, "test_gs_seek_with_buffer", "r");
        gridStore2.open(function(err, gridStore) {
          // Seek to start
          gridStore.seek(0, function(err, gridStore) {
            // Read first character and verify
            gridStore.getc(function(err, chr) {
              test.equal('h', chr);
            });
          });
        });

        // Open the file in read mode
        var gridStore3 = new GridStore(db, "test_gs_seek_with_buffer", "r");
        gridStore3.open(function(err, gridStore) {
          // Seek to 7 characters from the beginning off the file and verify
          gridStore.seek(7, function(err, gridStore) {
            gridStore.getc(function(err, chr) {
              test.equal('w', chr);
            });
          });
        });

        // Open the file in read mode
        var gridStore5 = new GridStore(db, "test_gs_seek_with_buffer", "r");
        gridStore5.open(function(err, gridStore) {
          // Seek to -1 characters from the end off the file and verify
          gridStore.seek(-1, GridStore.IO_SEEK_END, function(err, gridStore) {
            gridStore.getc(function(err, chr) {
              test.equal('!', chr);
            });
          });
        });

        // Open the file in read mode
        var gridStore6 = new GridStore(db, "test_gs_seek_with_buffer", "r");
        gridStore6.open(function(err, gridStore) {
          // Seek to -6 characters from the end off the file and verify
          gridStore.seek(-6, GridStore.IO_SEEK_END, function(err, gridStore) {
            gridStore.getc(function(err, chr) {
              test.equal('w', chr);
            });
          });
        });

        // Open the file in read mode
        var gridStore7 = new GridStore(db, "test_gs_seek_with_buffer", "r");
        gridStore7.open(function(err, gridStore) {

          // Seek forward 7 characters from the current read position and verify
          gridStore.seek(7, GridStore.IO_SEEK_CUR, function(err, gridStore) {
            gridStore.getc(function(err, chr) {
              test.equal('w', chr);

              // Seek forward -1 characters from the current read position and verify
              gridStore.seek(-1, GridStore.IO_SEEK_CUR, function(err, gridStore) {
                gridStore.getc(function(err, chr) {
                  test.equal('w', chr);

                  // Seek forward -4 characters from the current read position and verify
                  gridStore.seek(-4, GridStore.IO_SEEK_CUR, function(err, gridStore) {
                    gridStore.getc(function(err, chr) {
                      test.equal('o', chr);

                      // Seek forward 3 characters from the current read position and verify
                      gridStore.seek(3, GridStore.IO_SEEK_CUR, function(err, gridStore) {
                        gridStore.getc(function(err, chr) {
                          test.equal('o', chr);

                          db.close();
                        });
                      });
                    });
                  });
                });
              });
            });
          });
        });
      });
    });
  });
});

Return a modified Readable stream including a possible transform method.

Examples
// A simple example showing the usage of the stream method.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Open a file for reading
  var gridStoreR = new GridStore(db, "test_gs_read_stream", "r");
  // Open a file for writing
  var gridStoreW = new GridStore(db, "test_gs_read_stream", "w");
  // Read in the data of a file
  var data = fs.readFileSync("./test/functional/data/test_gs_weird_bug.png");

  var readLen = 0;
  var gotEnd = 0;

  // Open the file we are writting to
  gridStoreW.open(function(err, gs) {
    // Write the file content
    gs.write(data, function(err, gs) {
      // Flush the file to GridFS
      gs.close(function(err, result) {

        // Open the read file
        gridStoreR.open(function(err, gs) {
          // Create a stream to the file
          var stream = gs.stream();

          // Register events
          stream.on("data", function(chunk) {
            // Record the length of the file
            readLen += chunk.length;
          });

          stream.on("end", function() {
            // Verify the correctness of the read data
            test.equal(data.length, readLen);
            db.close();
          });
        });
      });
    });
  });
});
// A simple example showing how to pipe a to a gridstore object

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Set up gridStore
  var gridStore = new GridStore(client, "test_stream_write", "w");
  var stream = gridStore.stream();
  // Create a file reader stream to an object
  var fileStream = fs.createReadStream("./test/functional/data/test_gs_working_field_read.pdf");
  stream.on("end", function(err) {
    // Just read the content and compare to the raw binary
    GridStore.read(client, "test_stream_write", function(err, gridData) {
      var fileData = fs.readFileSync("./test/functional/data/test_gs_working_field_read.pdf");
      test.equal(fileData.toString('hex'), gridData.toString('hex'));
      client.close();
    })
  });

  // Pipe it through to the gridStore
  fileStream.pipe(stream);
});
// A simple example showing how to pipe a file stream through from gridfs to a file

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Open a file for writing
  var gridStoreWrite = new GridStore(db, "test_gs_read_stream_pipe", "w", {chunkSize:1024});
  gridStoreWrite.writeFile("./test/functional/data/test_gs_weird_bug.png", function(err, result) {
    test.equal(null, err);
    test.ok(result != null);
    // Open the gridStore for reading and pipe to a file
    var gridStore = new GridStore(db, "test_gs_read_stream_pipe", "r");
    gridStore.open(function(err, gridStore) {
      // Create a file write stream
      var fileStream = fs.createWriteStream("./test_gs_weird_bug_streamed.tmp");
      // Grab the read stream
      var stream = gridStore.stream();
      // When the stream is finished close the database
      fileStream.on("close", function(err) {
        // Read the original content
        var originalData = fs.readFileSync("./test/functional/data/test_gs_weird_bug.png");
        // Ensure we are doing writing before attempting to open the file
        fs.readFile("./test_gs_weird_bug_streamed.tmp", function(err, streamedData) {
          // Compare the data
          for(var i = 0; i < originalData.length; i++) {
            test.equal(originalData[i], streamedData[i])
          }

          // Close the database
          db.close();
        });
      });

      // Pipe out the data
      stream.pipe(fileStream);
    })
  })
});

tell(length, buffer, callback){Promise}

Retrieves the position of the read/write head of this file.

Name Type Description
length number optional

the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified.

buffer string | Buffer optional

a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method.

callback GridStore~tellCallback optional

the command callback.

Returns:
Promise if no callback passed
Examples
// A simple example showing the usage of the tell method.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create a new file
  var gridStore = new GridStore(db, "test_gs_tell", "w");
  // Open the file
  gridStore.open(function(err, gridStore) {
    // Write a string to the file
    gridStore.write("hello, world!", function(err, gridStore) {
      // Flush the file to GridFS
      gridStore.close(function(err, result) {

        // Open the file in read only mode
        var gridStore2 = new GridStore(db, "test_gs_tell", "r");
        gridStore2.open(function(err, gridStore) {

          // Read the first 5 characters
          gridStore.read(5, function(err, data) {
            test.equal("hello", data);

            // Get the current position of the read head
            gridStore.tell(function(err, position) {
              test.equal(5, position);

              db.close();
            });
          });
        });
      });
    });
  });
});
// A simple example showing the usage of the tell method using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Create a new file
  var gridStore = new GridStore(db, "test_gs_tell", "w");
  // Open the file
  gridStore.open().then(function(gridStore) {
    // Write a string to the file
    gridStore.write("hello, world!").then(function(gridStore) {
      // Flush the file to GridFS
      gridStore.close().then(function(result) {

        // Open the file in read only mode
        var gridStore2 = new GridStore(db, "test_gs_tell", "r");
        gridStore2.open().then(function(gridStore) {

          // Read the first 5 characters
          gridStore.read(5).then(function(data) {
            test.equal("hello", data);

            // Get the current position of the read head
            gridStore.tell().then(function(position) {
              test.equal(5, position);

              db.close();
            });
          });
        });
      });
    });
  });
});
// A simple example showing the usage of the tell method using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Create a new file
  var gridStore = new GridStore(db, "test_gs_tell", "w");
  // Open the file
  yield gridStore.open();
  // Write a string to the file
  yield gridStore.write("hello, world!");
  // Flush the file to GridFS
  yield gridStore.close();

  // Open the file in read only mode
  var gridStore = new GridStore(db, "test_gs_tell", "r");
  yield gridStore.open();

  // Read the first 5 characters
  var data = yield gridStore.read(5);
  test.equal("hello", data);

  // Get the current position of the read head
  var position = yield gridStore.tell();
  test.equal(5, position);

  db.close();
});

Deletes all the chunks of this file in the database.

Name Type Description
callback GridStore~resultCallback optional

the command callback.

Returns:
Promise if no callback passed
Examples
// A simple example showing how to use the instance level unlink command to delete a gridstore item.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  gridStore.open(function(err, gridStore) {

    // Write a text string
    gridStore.write('Hello world', function(err, gridStore) {

      // Close the
      gridStore.close(function(err, result) {
        test.equal(err, null);

        // Open the file again and unlin it
        new GridStore(db, fileId, 'r').open(function(err, gridStore) {

          // Unlink the file
          gridStore.unlink(function(err, result) {
            test.equal(null, err);

            // Verify that the file no longer exists
            GridStore.exist(db, fileId, function(err, result) {
              test.equal(null, err);
              test.equal(false, result);

              db.close();
            });
          });
        });
      });
    });
  });
});
// A simple example showing how to use the instance level unlink command to delete a gridstore item using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  gridStore.open().then(function(gridStore) {

    // Write a text string
    gridStore.write('Hello world').then(function(gridStore) {

      // Close the
      gridStore.close().then(function(result) {

        // Open the file again and unlin it
        new GridStore(db, fileId, 'r').open().then(function(gridStore) {

          // Unlink the file
          gridStore.unlink().then(function(result) {

            // Verify that the file no longer exists
            GridStore.exist(db, fileId).then(function(result) {
              test.equal(false, result);

              db.close();
            });
          });
        });
      });
    });
  });
});
// A simple example showing how to use the instance level unlink command to delete a gridstore item using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  yield gridStore.open();

  // Write a text string
  yield gridStore.write('Hello world');

  // Close the
  yield gridStore.close();

  // Open the file again and unlin it
  gridStore = yield new GridStore(db, fileId, 'r').open();

  // Unlink the file
  yield gridStore.unlink();

  // Verify that the file no longer exists
  var result = yield GridStore.exist(db, fileId);
  test.equal(false, result);

  db.close();
});

write(data, close, callback){Promise}

Writes some data. This method will work properly only if initialized with mode "w" or "w+".

Name Type Description
data string | Buffer

the data to write.

close boolean optional

closes this file after writing if set to true.

callback GridStore~resultCallback optional

this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.

Returns:
Promise if no callback passed
Examples
// A simple example showing how to use the write command with strings and Buffers.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  gridStore.open(function(err, gridStore) {

    // Write a text string
    gridStore.write('Hello world', function(err, gridStore) {

      // Write a buffer
      gridStore.write(new Buffer('Buffer Hello world'), function(err, gridStore) {

        // Close the
        gridStore.close(function(err, result) {

          // Read back all the written content and verify the correctness
          GridStore.read(db, fileId, function(err, fileData) {
            test.equal('Hello worldBuffer Hello world', fileData.toString());

            db.close();
          });
        });
      });
    });
  });
});
// A simple example showing how to use the write command with strings and Buffers using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  gridStore.open().then(function(gridStore) {

    // Write a text string
    gridStore.write('Hello world').then(function(gridStore) {

      // Write a buffer
      gridStore.write(new Buffer('Buffer Hello world')).then(function(gridStore) {

        // Close the
        gridStore.close().then(function(result) {

          // Read back all the written content and verify the correctness
          GridStore.read(db, fileId).then(function(fileData) {
            test.equal('Hello worldBuffer Hello world', fileData.toString());

            db.close();
          });
        });
      });
    });
  });
});
// A simple example showing how to use the write command with strings and Buffers using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Open the new file
  yield gridStore.open();

  // Write a text string
  yield gridStore.write('Hello world');

  // Write a buffer
  yield gridStore.write(new Buffer('Buffer Hello world'));

  // Close the
  yield gridStore.close();

  // Read back all the written content and verify the correctness
  var fileData = yield GridStore.read(db, fileId);
  test.equal('Hello worldBuffer Hello world', fileData.toString());

  db.close();
});

writeFile(file, callback){Promise}

Stores a file from the file system to the GridFS database.

Name Type Description
file string | Buffer | FileHandle

the file to store.

callback GridStore~resultCallback optional

this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object.

Returns:
Promise if no callback passed
Examples
// A simple example showing how to write a file to Gridstore using file location path.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Read the filesize of file on disk (provide your own)
  var fileSize = fs.statSync('./test/functional/data/test_gs_weird_bug.png').size;
  // Read the buffered data for comparision reasons
  var data = fs.readFileSync('./test/functional/data/test_gs_weird_bug.png');

  // Open the new file
  gridStore.open(function(err, gridStore) {

    // Write the file to gridFS
    gridStore.writeFile('./test/functional/data/test_gs_weird_bug.png', function(err, doc) {

      // Read back all the written content and verify the correctness
      GridStore.read(db, fileId, function(err, fileData) {
        test.equal(data.toString('base64'), fileData.toString('base64'))
        test.equal(fileSize, fileData.length);

        db.close();
      });
    });
  });
});
// A simple example showing how to write a file to Gridstore using a file handle.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Read the filesize of file on disk (provide your own)
  var fileSize = fs.statSync('./test/functional/data/test_gs_weird_bug.png').size;
  // Read the buffered data for comparision reasons
  var data = fs.readFileSync('./test/functional/data/test_gs_weird_bug.png');

  // Open a file handle for reading the file
  var fd = fs.openSync('./test/functional/data/test_gs_weird_bug.png', 'r', parseInt('0666',8));

  // Open the new file
  gridStore.open(function(err, gridStore) {

    // Write the file to gridFS using the file handle
    gridStore.writeFile(fd, function(err, doc) {

      // Read back all the written content and verify the correctness
      GridStore.read(db, fileId, function(err, fileData) {
        test.equal(data.toString('base64'), fileData.toString('base64'));
        test.equal(fileSize, fileData.length);

        db.close();
      });
    });
  });
});
// A simple example showing how to write a file to Gridstore using file location path using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Read the filesize of file on disk (provide your own)
  var fileSize = fs.statSync('./test/functional/data/test_gs_weird_bug.png').size;
  // Read the buffered data for comparision reasons
  var data = fs.readFileSync('./test/functional/data/test_gs_weird_bug.png');

  // Open the new file
  gridStore.open().then(function(gridStore) {

    // Write the file to gridFS
    gridStore.writeFile('./test/functional/data/test_gs_weird_bug.png').then(function(doc) {

      // Read back all the written content and verify the correctness
      GridStore.read(db, fileId).then(function(fileData) {
        test.equal(data.toString('base64'), fileData.toString('base64'))
        test.equal(fileSize, fileData.length);

        db.close();
      });
    });
  });
});
// A simple example showing how to write a file to Gridstore using a file handle using a Promise.

var MongoClient = require('mongodb').MongoClient,
  GridStore = require('mongodb').GridStore,
  ObjectID = require('mongodb').ObjectID,
  test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Read the filesize of file on disk (provide your own)
  var fileSize = fs.statSync('./test/functional/data/test_gs_weird_bug.png').size;
  // Read the buffered data for comparision reasons
  var data = fs.readFileSync('./test/functional/data/test_gs_weird_bug.png');

  // Open a file handle for reading the file
  var fd = fs.openSync('./test/functional/data/test_gs_weird_bug.png', 'r', parseInt('0666',8));

  // Open the new file
  gridStore.open().then(function(gridStore) {

    // Write the file to gridFS using the file handle
    gridStore.writeFile(fd).then(function(doc) {

      // Read back all the written content and verify the correctness
      GridStore.read(db, fileId).then(function(fileData) {
        test.equal(data.toString('base64'), fileData.toString('base64'));
        test.equal(fileSize, fileData.length);

        db.close();
      });
    });
  });
});
// A simple example showing how to write a file to Gridstore using file location path using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Read the filesize of file on disk (provide your own)
  var fileSize = fs.statSync('./test/functional/data/test_gs_weird_bug.png').size;
  // Read the buffered data for comparision reasons
  var data = fs.readFileSync('./test/functional/data/test_gs_weird_bug.png');

  // Open the new file
  yield gridStore.open();

  // Write the file to gridFS
  yield gridStore.writeFile('./test/functional/data/test_gs_weird_bug.png');

  // Read back all the written content and verify the correctness
  var fileData = yield GridStore.read(db, fileId);
  test.equal(data.toString('base64'), fileData.toString('base64'))
  test.equal(fileSize, fileData.length);

  db.close();
});
// A simple example showing how to write a file to Gridstore using a file handle using a Generator and the co module.

var MongoClient = require('mongodb').MongoClient,
  co = require('co');
  test = require('assert');

co(function*() {
  var db = yield MongoClient.connect('mongodb://localhost:27017/test');
  // Our file ID
  var fileId = new ObjectID();

  // Open a new file
  var gridStore = new GridStore(db, fileId, 'w');

  // Read the filesize of file on disk (provide your own)
  var fileSize = fs.statSync('./test/functional/data/test_gs_weird_bug.png').size;
  // Read the buffered data for comparision reasons
  var data = fs.readFileSync('./test/functional/data/test_gs_weird_bug.png');

  // Open a file handle for reading the file
  var fd = fs.openSync('./test/functional/data/test_gs_weird_bug.png', 'r', parseInt('0666',8));

  // Open the new file
  yield gridStore.open();

  // Write the file to gridFS using the file handle
  yield gridStore.writeFile(fd);

  // Read back all the written content and verify the correctness
  var fileData = yield GridStore.read(db, fileId);
  test.equal(data.toString('base64'), fileData.toString('base64'));
  test.equal(fileSize, fileData.length);

  db.close();
});

Type Definitions

collectionCallback(error, collection)

The collection callback format.

Name Type Description
error MongoError

An error instance representing the error during the execution.

collection Collection

The collection from the command execution.

gridStoreCallback(error, gridStore)

The tell callback format.

Name Type Description
error MongoError

An error instance representing the error during the execution.

gridStore GridStore

The gridStore.

openCallback(error, gridStore)

The callback format for the Gridstore.open method

Name Type Description
error MongoError

An error instance representing the error during the execution.

gridStore GridStore

The GridStore instance if the open method was successful.

readCallback(error, data)

The read callback format.

Name Type Description
error MongoError

An error instance representing the error during the execution.

data Buffer

The data read from the GridStore object

readlinesCallback(error, strings)

The readlines callback format.

Name Type Description
error MongoError

An error instance representing the error during the execution.

strings Array.<string>

The array of strings returned.

resultCallback(error, result)

The callback result format.

Name Type Description
error MongoError

An error instance representing the error during the execution.

result object

The result from the callback.

tellCallback(error, position)

The tell callback format.

Name Type Description
error MongoError

An error instance representing the error during the execution.

position number

The current read position in the GridStore.

comments powered by Disqus