4 * @fileOverview GridFS is a tool for MongoDB to store files to the database.
5 * Because of the restrictions of the object size the database can hold, a
6 * facility to split a file into several chunks is needed. The {@link GridStore}
7 * class offers a simplified api to interact with files while managing the
8 * chunks of split files behind the scenes. More information about GridFS can be
9 * found <a href="http://www.mongodb.org/display/DOCS/GridFS">here</a>.
12 * var MongoClient = require('mongodb').MongoClient,
13 * GridStore = require('mongodb').GridStore,
14 * ObjectID = require('mongodb').ObjectID,
15 * test = require('assert');
18 * var url = 'mongodb://localhost:27017/test';
19 * // Connect using MongoClient
20 * MongoClient.connect(url, function(err, db) {
21 * var gridStore = new GridStore(db, null, "w");
22 * gridStore.open(function(err, gridStore) {
23 * gridStore.write("hello world!", function(err, gridStore) {
24 * gridStore.close(function(err, result) {
26 * // Let's read the file using object Id
27 * GridStore.read(db, result._id, function(err, data) {
28 * test.equal('hello world!', data);
37 var Chunk = require('./chunk'),
38 ObjectID = require('mongodb-core').BSON.ObjectID,
39 ReadPreference = require('../read_preference'),
40 Buffer = require('buffer').Buffer,
41 Collection = require('../collection'),
43 timers = require('timers'),
44 f = require('util').format,
45 util = require('util'),
46 Define = require('../metadata'),
47 MongoError = require('mongodb-core').MongoError,
48 inherits = util.inherits,
49 Duplex = require('stream').Duplex || require('readable-stream').Duplex,
50 shallowClone = require('../utils').shallowClone;
52 var REFERENCE_BY_FILENAME = 0,
56 * Namespace provided by the mongodb-core and node.js
61 * Create a new GridStore instance
64 * - **"r"** - read only. This is the default mode.
65 * - **"w"** - write in truncate mode. Existing data will be overwriten.
68 * @param {Db} db A database instance to interact with.
69 * @param {object} [id] optional unique id for this file
70 * @param {string} [filename] optional filename for this file, no unique constrain on the field
71 * @param {string} mode set the mode for this file.
72 * @param {object} [options=null] Optional settings.
73 * @param {(number|string)} [options.w=null] The write concern.
74 * @param {number} [options.wtimeout=null] The write concern timeout.
75 * @param {boolean} [options.j=false] Specify a journal write concern.
76 * @param {boolean} [options.fsync=false] Specify a file sync write concern.
77 * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.
78 * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**.
79 * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**.
80 * @param {object} [options.metadata=null] Arbitrary data the user wants to store.
81 * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
82 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
83 * @property {number} chunkSize Get the gridstore chunk size.
84 * @property {number} md5 The md5 checksum for this file.
85 * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory
86 * @return {GridStore} a GridStore instance.
87 * @deprecated Use GridFSBucket API instead
89 var GridStore = function GridStore(db, id, filename, mode, options) {
90 if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options);
95 if(typeof options === 'undefined') options = {};
97 if(typeof mode === 'undefined') {
100 } else if(typeof mode == 'object') {
103 filename = undefined;
106 if(id instanceof ObjectID) {
107 this.referenceBy = REFERENCE_BY_ID;
109 this.filename = filename;
110 } else if(typeof filename == 'undefined') {
111 this.referenceBy = REFERENCE_BY_FILENAME;
113 if (mode.indexOf('w') != null) {
114 this.fileId = new ObjectID();
117 this.referenceBy = REFERENCE_BY_ID;
119 this.filename = filename;
123 this.mode = mode == null ? "r" : mode;
124 this.options = options || {};
129 // Set the root if overridden
130 this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root'];
132 this.readPreference = this.options.readPreference || db.options.readPreference || ReadPreference.PRIMARY;
133 this.writeConcern = _getWriteConcern(db, this.options);
134 // Set default chunk size
135 this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize'];
137 // Get the promiseLibrary
138 var promiseLibrary = this.options.promiseLibrary;
140 // No promise library selected fall back
141 if(!promiseLibrary) {
142 promiseLibrary = typeof global.Promise == 'function' ?
143 global.Promise : require('es6-promise').Promise;
146 // Set the promiseLibrary
147 this.promiseLibrary = promiseLibrary;
149 Object.defineProperty(this, "chunkSize", { enumerable: true
151 return this.internalChunkSize;
153 , set: function(value) {
154 if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) {
155 this.internalChunkSize = this.internalChunkSize;
157 this.internalChunkSize = value;
162 Object.defineProperty(this, "md5", { enumerable: true
164 return this.internalMd5;
168 Object.defineProperty(this, "chunkNumber", { enumerable: true
170 return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null;
175 var define = GridStore.define = new Define('Gridstore', GridStore, true);
178 * The callback format for the Gridstore.open method
179 * @callback GridStore~openCallback
180 * @param {MongoError} error An error instance representing the error during the execution.
181 * @param {GridStore} gridStore The GridStore instance if the open method was successful.
185 * Opens the file from the database and initialize this object. Also creates a
186 * new one if file does not exist.
189 * @param {GridStore~openCallback} [callback] this will be called after executing this method
190 * @return {Promise} returns Promise if no callback passed
191 * @deprecated Use GridFSBucket API instead
193 GridStore.prototype.open = function(callback) {
195 if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){
196 throw MongoError.create({message: "Illegal mode " + this.mode, driver:true});
199 // We provided a callback leg
200 if(typeof callback == 'function') return open(self, callback);
202 return new self.promiseLibrary(function(resolve, reject) {
203 open(self, function(err, store) {
204 if(err) return reject(err);
210 var open = function(self, callback) {
211 // Get the write concern
212 var writeConcern = _getWriteConcern(self.db, self.options);
214 // If we are writing we need to ensure we have the right indexes for md5's
215 if((self.mode == "w" || self.mode == "w+")) {
216 // Get files collection
217 var collection = self.collection();
218 // Put index on filename
219 collection.ensureIndex([['filename', 1]], writeConcern, function(err, index) {
220 // Get chunk collection
221 var chunkCollection = self.chunkCollection();
222 // Make an unique index for compatibility with mongo-cxx-driver:legacy
223 var chunkIndexOptions = shallowClone(writeConcern);
224 chunkIndexOptions.unique = true;
225 // Ensure index on chunk collection
226 chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function(err, index) {
227 // Open the connection
228 _open(self, writeConcern, function(err, r) {
229 if(err) return callback(err);
236 // Open the gridstore
237 _open(self, writeConcern, function(err, r) {
238 if(err) return callback(err);
245 // Push the definition for open
246 define.classMethod('open', {callback: true, promise:true});
249 * Verify if the file is at EOF.
252 * @return {boolean} true if the read/write head is at the end of this file.
253 * @deprecated Use GridFSBucket API instead
255 GridStore.prototype.eof = function() {
256 return this.position == this.length ? true : false;
259 define.classMethod('eof', {callback: false, promise:false, returns: [Boolean]});
262 * The callback result format.
263 * @callback GridStore~resultCallback
264 * @param {MongoError} error An error instance representing the error during the execution.
265 * @param {object} result The result from the callback.
269 * Retrieves a single character from this file.
272 * @param {GridStore~resultCallback} [callback] 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.
273 * @return {Promise} returns Promise if no callback passed
274 * @deprecated Use GridFSBucket API instead
276 GridStore.prototype.getc = function(callback) {
278 // We provided a callback leg
279 if(typeof callback == 'function') return eof(self, callback);
281 return new self.promiseLibrary(function(resolve, reject) {
282 eof(self, function(err, r) {
283 if(err) return reject(err);
289 var eof = function(self, callback) {
291 callback(null, null);
292 } else if(self.currentChunk.eof()) {
293 nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) {
294 self.currentChunk = chunk;
295 self.position = self.position + 1;
296 callback(err, self.currentChunk.getc());
299 self.position = self.position + 1;
300 callback(null, self.currentChunk.getc());
304 define.classMethod('getc', {callback: true, promise:true});
307 * Writes a string to the file with a newline character appended at the end if
308 * the given string does not have one.
311 * @param {string} string the string to write.
312 * @param {GridStore~resultCallback} [callback] 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.
313 * @return {Promise} returns Promise if no callback passed
314 * @deprecated Use GridFSBucket API instead
316 GridStore.prototype.puts = function(string, callback) {
318 var finalString = string.match(/\n$/) == null ? string + "\n" : string;
319 // We provided a callback leg
320 if(typeof callback == 'function') return this.write(finalString, callback);
322 return new self.promiseLibrary(function(resolve, reject) {
323 self.write(finalString, function(err, r) {
324 if(err) return reject(err);
330 define.classMethod('puts', {callback: true, promise:true});
333 * Return a modified Readable stream including a possible transform method.
336 * @return {GridStoreStream}
337 * @deprecated Use GridFSBucket API instead
339 GridStore.prototype.stream = function() {
340 return new GridStoreStream(this);
343 define.classMethod('stream', {callback: false, promise:false, returns: [GridStoreStream]});
346 * Writes some data. This method will work properly only if initialized with mode "w" or "w+".
349 * @param {(string|Buffer)} data the data to write.
350 * @param {boolean} [close] closes this file after writing if set to true.
351 * @param {GridStore~resultCallback} [callback] 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.
352 * @return {Promise} returns Promise if no callback passed
353 * @deprecated Use GridFSBucket API instead
355 GridStore.prototype.write = function write(data, close, callback) {
357 // We provided a callback leg
358 if(typeof callback == 'function') return _writeNormal(this, data, close, callback);
360 return new self.promiseLibrary(function(resolve, reject) {
361 _writeNormal(self, data, close, function(err, r) {
362 if(err) return reject(err);
368 define.classMethod('write', {callback: true, promise:true});
371 * Handles the destroy part of a stream
375 * @deprecated Use GridFSBucket API instead
377 GridStore.prototype.destroy = function destroy() {
378 // close and do not emit any more events. queued data is not sent.
379 if(!this.writable) return;
380 this.readable = false;
382 this.writable = false;
388 define.classMethod('destroy', {callback: false, promise:false});
391 * Stores a file from the file system to the GridFS database.
394 * @param {(string|Buffer|FileHandle)} file the file to store.
395 * @param {GridStore~resultCallback} [callback] 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.
396 * @return {Promise} returns Promise if no callback passed
397 * @deprecated Use GridFSBucket API instead
399 GridStore.prototype.writeFile = function (file, callback) {
401 // We provided a callback leg
402 if(typeof callback == 'function') return writeFile(self, file, callback);
404 return new self.promiseLibrary(function(resolve, reject) {
405 writeFile(self, file, function(err, r) {
406 if(err) return reject(err);
412 var writeFile = function(self, file, callback) {
413 if (typeof file === 'string') {
414 fs.open(file, 'r', function (err, fd) {
415 if(err) return callback(err);
416 self.writeFile(fd, callback);
421 self.open(function (err, self) {
422 if(err) return callback(err, self);
424 fs.fstat(file, function (err, stats) {
425 if(err) return callback(err, self);
429 var numberOfChunksLeft = Math.min(stats.size / self.chunkSize);
432 var writeChunk = function() {
433 fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) {
434 if(err) return callback(err, self);
436 offset = offset + bytesRead;
438 // Create a new chunk for the data
439 var chunk = new Chunk(self, {n:index++}, self.writeConcern);
440 chunk.write(data, function(err, chunk) {
441 if(err) return callback(err, self);
443 chunk.save({}, function(err, result) {
444 if(err) return callback(err, self);
446 self.position = self.position + data.length;
448 // Point to current chunk
449 self.currentChunk = chunk;
451 if(offset >= stats.size) {
453 self.close(function(err, result) {
454 if(err) return callback(err, self);
455 return callback(null, self);
458 return process.nextTick(writeChunk);
465 // Process the first write
466 process.nextTick(writeChunk);
471 define.classMethod('writeFile', {callback: true, promise:true});
474 * Saves this file to the database. This will overwrite the old entry if it
475 * already exists. This will work properly only if mode was initialized to
479 * @param {GridStore~resultCallback} [callback] 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.
480 * @return {Promise} returns Promise if no callback passed
481 * @deprecated Use GridFSBucket API instead
483 GridStore.prototype.close = function(callback) {
485 // We provided a callback leg
486 if(typeof callback == 'function') return close(self, callback);
488 return new self.promiseLibrary(function(resolve, reject) {
489 close(self, function(err, r) {
490 if(err) return reject(err);
496 var close = function(self, callback) {
497 if(self.mode[0] == "w") {
499 var options = self.writeConcern;
501 if(self.currentChunk != null && self.currentChunk.position > 0) {
502 self.currentChunk.save({}, function(err, chunk) {
503 if(err && typeof callback == 'function') return callback(err);
505 self.collection(function(err, files) {
506 if(err && typeof callback == 'function') return callback(err);
508 // Build the mongo object
509 if(self.uploadDate != null) {
510 buildMongoObject(self, function(err, mongoObject) {
512 if(typeof callback == 'function') return callback(err); else throw err;
515 files.save(mongoObject, options, function(err) {
516 if(typeof callback == 'function')
517 callback(err, mongoObject);
521 self.uploadDate = new Date();
522 buildMongoObject(self, function(err, mongoObject) {
524 if(typeof callback == 'function') return callback(err); else throw err;
527 files.save(mongoObject, options, function(err) {
528 if(typeof callback == 'function')
529 callback(err, mongoObject);
536 self.collection(function(err, files) {
537 if(err && typeof callback == 'function') return callback(err);
539 self.uploadDate = new Date();
540 buildMongoObject(self, function(err, mongoObject) {
542 if(typeof callback == 'function') return callback(err); else throw err;
545 files.save(mongoObject, options, function(err) {
546 if(typeof callback == 'function')
547 callback(err, mongoObject);
552 } else if(self.mode[0] == "r") {
553 if(typeof callback == 'function')
554 callback(null, null);
556 if(typeof callback == 'function')
557 callback(MongoError.create({message: f("Illegal mode %s", self.mode), driver:true}));
561 define.classMethod('close', {callback: true, promise:true});
564 * The collection callback format.
565 * @callback GridStore~collectionCallback
566 * @param {MongoError} error An error instance representing the error during the execution.
567 * @param {Collection} collection The collection from the command execution.
571 * Retrieve this file's chunks collection.
574 * @param {GridStore~collectionCallback} callback the command callback.
575 * @return {Collection}
576 * @deprecated Use GridFSBucket API instead
578 GridStore.prototype.chunkCollection = function(callback) {
579 if(typeof callback == 'function')
580 return this.db.collection((this.root + ".chunks"), callback);
581 return this.db.collection((this.root + ".chunks"));
584 define.classMethod('chunkCollection', {callback: true, promise:false, returns: [Collection]});
587 * Deletes all the chunks of this file in the database.
590 * @param {GridStore~resultCallback} [callback] the command callback.
591 * @return {Promise} returns Promise if no callback passed
592 * @deprecated Use GridFSBucket API instead
594 GridStore.prototype.unlink = function(callback) {
596 // We provided a callback leg
597 if(typeof callback == 'function') return unlink(self, callback);
599 return new self.promiseLibrary(function(resolve, reject) {
600 unlink(self, function(err, r) {
601 if(err) return reject(err);
607 var unlink = function(self, callback) {
608 deleteChunks(self, function(err) {
610 err.message = "at deleteChunks: " + err.message;
611 return callback(err);
614 self.collection(function(err, collection) {
616 err.message = "at collection: " + err.message;
617 return callback(err);
620 collection.remove({'_id':self.fileId}, self.writeConcern, function(err) {
627 define.classMethod('unlink', {callback: true, promise:true});
630 * Retrieves the file collection associated with this object.
633 * @param {GridStore~collectionCallback} callback the command callback.
634 * @return {Collection}
635 * @deprecated Use GridFSBucket API instead
637 GridStore.prototype.collection = function(callback) {
638 if(typeof callback == 'function')
639 this.db.collection(this.root + ".files", callback);
640 return this.db.collection(this.root + ".files");
643 define.classMethod('collection', {callback: true, promise:false, returns: [Collection]});
646 * The readlines callback format.
647 * @callback GridStore~readlinesCallback
648 * @param {MongoError} error An error instance representing the error during the execution.
649 * @param {string[]} strings The array of strings returned.
653 * Read the entire file as a list of strings splitting by the provided separator.
656 * @param {string} [separator] The character to be recognized as the newline separator.
657 * @param {GridStore~readlinesCallback} [callback] the command callback.
658 * @return {Promise} returns Promise if no callback passed
659 * @deprecated Use GridFSBucket API instead
661 GridStore.prototype.readlines = function(separator, callback) {
663 var args = Array.prototype.slice.call(arguments, 0);
664 callback = args.pop();
665 if(typeof callback != 'function') args.push(callback);
666 separator = args.length ? args.shift() : "\n";
667 separator = separator || "\n";
669 // We provided a callback leg
670 if(typeof callback == 'function') return readlines(self, separator, callback);
673 return new self.promiseLibrary(function(resolve, reject) {
674 readlines(self, separator, function(err, r) {
675 if(err) return reject(err);
681 var readlines = function(self, separator, callback) {
682 self.read(function(err, data) {
683 if(err) return callback(err);
685 var items = data.toString().split(separator);
686 items = items.length > 0 ? items.splice(0, items.length - 1) : [];
687 for(var i = 0; i < items.length; i++) {
688 items[i] = items[i] + separator;
691 callback(null, items);
695 define.classMethod('readlines', {callback: true, promise:true});
698 * Deletes all the chunks of this file in the database if mode was set to "w" or
699 * "w+" and resets the read/write head to the initial position.
702 * @param {GridStore~resultCallback} [callback] 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.
703 * @return {Promise} returns Promise if no callback passed
704 * @deprecated Use GridFSBucket API instead
706 GridStore.prototype.rewind = function(callback) {
708 // We provided a callback leg
709 if(typeof callback == 'function') return rewind(self, callback);
711 return new self.promiseLibrary(function(resolve, reject) {
712 rewind(self, function(err, r) {
713 if(err) return reject(err);
719 var rewind = function(self, callback) {
720 if(self.currentChunk.chunkNumber != 0) {
721 if(self.mode[0] == "w") {
722 deleteChunks(self, function(err, gridStore) {
723 if(err) return callback(err);
724 self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern);
726 callback(null, self);
729 self.currentChunk(0, function(err, chunk) {
730 if(err) return callback(err);
731 self.currentChunk = chunk;
732 self.currentChunk.rewind();
734 callback(null, self);
738 self.currentChunk.rewind();
740 callback(null, self);
744 define.classMethod('rewind', {callback: true, promise:true});
747 * The read callback format.
748 * @callback GridStore~readCallback
749 * @param {MongoError} error An error instance representing the error during the execution.
750 * @param {Buffer} data The data read from the GridStore object
754 * Retrieves the contents of this file and advances the read/write head. Works with Buffers only.
756 * There are 3 signatures for this method:
760 * (length, buffer, callback)
763 * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified.
764 * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method.
765 * @param {GridStore~readCallback} [callback] the command callback.
766 * @return {Promise} returns Promise if no callback passed
767 * @deprecated Use GridFSBucket API instead
769 GridStore.prototype.read = function(length, buffer, callback) {
772 var args = Array.prototype.slice.call(arguments, 0);
773 callback = args.pop();
774 if(typeof callback != 'function') args.push(callback);
775 length = args.length ? args.shift() : null;
776 buffer = args.length ? args.shift() : null;
777 // We provided a callback leg
778 if(typeof callback == 'function') return read(self, length, buffer, callback);
780 return new self.promiseLibrary(function(resolve, reject) {
781 read(self, length, buffer, function(err, r) {
782 if(err) return reject(err);
788 var read = function(self, length, buffer, callback) {
789 // The data is a c-terminated string and thus the length - 1
790 var finalLength = length == null ? self.length - self.position : length;
791 var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer;
792 // Add a index to buffer to keep track of writing position or apply current index
793 finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0;
795 if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) {
796 var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index);
797 // Copy content to final buffer
798 slice.copy(finalBuffer, finalBuffer._index);
799 // Update internal position
800 self.position = self.position + finalBuffer.length;
801 // Check if we don't have a file at all
802 if(finalLength == 0 && finalBuffer.length == 0) return callback(MongoError.create({message: "File does not exist", driver:true}), null);
804 return callback(null, finalBuffer);
807 // Read the next chunk
808 var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position);
809 // Copy content to final buffer
810 slice.copy(finalBuffer, finalBuffer._index);
811 // Update index position
812 finalBuffer._index += slice.length;
814 // Load next chunk and read more
815 nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) {
816 if(err) return callback(err);
818 if(chunk.length() > 0) {
819 self.currentChunk = chunk;
820 self.read(length, finalBuffer, callback);
822 if(finalBuffer._index > 0) {
823 callback(null, finalBuffer)
825 callback(MongoError.create({message: "no chunks found for file, possibly corrupt", driver:true}), null);
831 define.classMethod('read', {callback: true, promise:true});
834 * The tell callback format.
835 * @callback GridStore~tellCallback
836 * @param {MongoError} error An error instance representing the error during the execution.
837 * @param {number} position The current read position in the GridStore.
841 * Retrieves the position of the read/write head of this file.
844 * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified.
845 * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method.
846 * @param {GridStore~tellCallback} [callback] the command callback.
847 * @return {Promise} returns Promise if no callback passed
848 * @deprecated Use GridFSBucket API instead
850 GridStore.prototype.tell = function(callback) {
852 // We provided a callback leg
853 if(typeof callback == 'function') return callback(null, this.position);
855 return new self.promiseLibrary(function(resolve, reject) {
856 resolve(self.position);
860 define.classMethod('tell', {callback: true, promise:true});
863 * The tell callback format.
864 * @callback GridStore~gridStoreCallback
865 * @param {MongoError} error An error instance representing the error during the execution.
866 * @param {GridStore} gridStore The gridStore.
870 * Moves the read/write head to a new location.
872 * There are 3 signatures for this method
874 * Seek Location Modes
875 * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file.
876 * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file.
877 * - **GridStore.IO_SEEK_END**, set the position from the end of the file.
880 * @param {number} [position] the position to seek to
881 * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes.
882 * @param {GridStore~gridStoreCallback} [callback] the command callback.
883 * @return {Promise} returns Promise if no callback passed
884 * @deprecated Use GridFSBucket API instead
886 GridStore.prototype.seek = function(position, seekLocation, callback) {
889 var args = Array.prototype.slice.call(arguments, 1);
890 callback = args.pop();
891 if(typeof callback != 'function') args.push(callback);
892 seekLocation = args.length ? args.shift() : null;
894 // We provided a callback leg
895 if(typeof callback == 'function') return seek(self, position, seekLocation, callback);
897 return new self.promiseLibrary(function(resolve, reject) {
898 seek(self, position, seekLocation, function(err, r) {
899 if(err) return reject(err);
905 var seek = function(self, position, seekLocation, callback) {
906 // Seek only supports read mode
907 if(self.mode != 'r') {
908 return callback(MongoError.create({message: "seek is only supported for mode r", driver:true}))
911 var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation;
912 var finalPosition = position;
913 var targetPosition = 0;
915 // Calculate the position
916 if(seekLocationFinal == GridStore.IO_SEEK_CUR) {
917 targetPosition = self.position + finalPosition;
918 } else if(seekLocationFinal == GridStore.IO_SEEK_END) {
919 targetPosition = self.length + finalPosition;
921 targetPosition = finalPosition;
925 var newChunkNumber = Math.floor(targetPosition/self.chunkSize);
926 var seekChunk = function() {
927 nthChunk(self, newChunkNumber, function(err, chunk) {
928 if(err) return callback(err, null);
929 if(chunk == null) return callback(new Error('no chunk found'));
931 // Set the current chunk
932 self.currentChunk = chunk;
933 self.position = targetPosition;
934 self.currentChunk.position = (self.position % self.chunkSize);
942 define.classMethod('seek', {callback: true, promise:true});
947 var _open = function(self, options, callback) {
948 var collection = self.collection();
950 var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename};
951 query = null == self.fileId && self.filename == null ? null : query;
952 options.readPreference = self.readPreference;
956 collection.findOne(query, options, function(err, doc) {
957 if(err) return error(err);
959 // Check if the collection for the files exists otherwise prepare the new one
961 self.fileId = doc._id;
962 // Prefer a new filename over the existing one if this is a write
963 self.filename = ((self.mode == 'r') || (self.filename == undefined)) ? doc.filename : self.filename;
964 self.contentType = doc.contentType;
965 self.internalChunkSize = doc.chunkSize;
966 self.uploadDate = doc.uploadDate;
967 self.aliases = doc.aliases;
968 self.length = doc.length;
969 self.metadata = doc.metadata;
970 self.internalMd5 = doc.md5;
971 } else if (self.mode != 'r') {
972 self.fileId = self.fileId == null ? new ObjectID() : self.fileId;
973 self.contentType = GridStore.DEFAULT_CONTENT_TYPE;
974 self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize;
978 var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId;
979 return error(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename)), driver:true}), self);
982 // Process the mode of the object
983 if(self.mode == "r") {
984 nthChunk(self, 0, options, function(err, chunk) {
985 if(err) return error(err);
986 self.currentChunk = chunk;
988 callback(null, self);
990 } else if(self.mode == "w" && doc) {
991 // Delete any existing chunks
992 deleteChunks(self, options, function(err, result) {
993 if(err) return error(err);
994 self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern);
995 self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type'];
996 self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];
997 self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
998 self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
1000 callback(null, self);
1002 } else if(self.mode == "w") {
1003 self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern);
1004 self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type'];
1005 self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];
1006 self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
1007 self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
1009 callback(null, self);
1010 } else if(self.mode == "w+") {
1011 nthChunk(self, lastChunkNumber(self), options, function(err, chunk) {
1012 if(err) return error(err);
1013 // Set the current chunk
1014 self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk;
1015 self.currentChunk.position = self.currentChunk.data.length();
1016 self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
1017 self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
1018 self.position = self.length;
1019 callback(null, self);
1025 self.fileId = null == self.fileId ? new ObjectID() : self.fileId;
1026 self.contentType = GridStore.DEFAULT_CONTENT_TYPE;
1027 self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize;
1030 var collection2 = self.chunkCollection();
1031 // No file exists set up write mode
1032 if(self.mode == "w") {
1033 // Delete any existing chunks
1034 deleteChunks(self, options, function(err, result) {
1035 if(err) return error(err);
1036 self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern);
1037 self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type'];
1038 self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];
1039 self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
1040 self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
1042 callback(null, self);
1044 } else if(self.mode == "w+") {
1045 nthChunk(self, lastChunkNumber(self), options, function(err, chunk) {
1046 if(err) return error(err);
1047 // Set the current chunk
1048 self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk;
1049 self.currentChunk.position = self.currentChunk.data.length();
1050 self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
1051 self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
1052 self.position = self.length;
1053 callback(null, self);
1058 // only pass error to callback once
1059 function error (err) {
1060 if(error.err) return;
1061 callback(error.err = err);
1068 var writeBuffer = function(self, buffer, close, callback) {
1069 if(typeof close === "function") { callback = close; close = null; }
1070 var finalClose = typeof close == 'boolean' ? close : false;
1072 if(self.mode != "w") {
1073 callback(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? self.referenceBy : self.filename)), driver:true}), null);
1075 if(self.currentChunk.position + buffer.length >= self.chunkSize) {
1076 // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left
1077 // to a new chunk (recursively)
1078 var previousChunkNumber = self.currentChunk.chunkNumber;
1079 var leftOverDataSize = self.chunkSize - self.currentChunk.position;
1080 var firstChunkData = buffer.slice(0, leftOverDataSize);
1081 var leftOverData = buffer.slice(leftOverDataSize);
1082 // A list of chunks to write out
1083 var chunksToWrite = [self.currentChunk.write(firstChunkData)];
1084 // If we have more data left than the chunk size let's keep writing new chunks
1085 while(leftOverData.length >= self.chunkSize) {
1086 // Create a new chunk and write to it
1087 var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern);
1088 var firstChunkData = leftOverData.slice(0, self.chunkSize);
1089 leftOverData = leftOverData.slice(self.chunkSize);
1090 // Update chunk number
1091 previousChunkNumber = previousChunkNumber + 1;
1093 newChunk.write(firstChunkData);
1094 // Push chunk to save list
1095 chunksToWrite.push(newChunk);
1098 // Set current chunk with remaining data
1099 self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern);
1100 // If we have left over data write it
1101 if(leftOverData.length > 0) self.currentChunk.write(leftOverData);
1103 // Update the position for the gridstore
1104 self.position = self.position + buffer.length;
1105 // Total number of chunks to write
1106 var numberOfChunksToWrite = chunksToWrite.length;
1108 for(var i = 0; i < chunksToWrite.length; i++) {
1109 chunksToWrite[i].save({}, function(err, result) {
1110 if(err) return callback(err);
1112 numberOfChunksToWrite = numberOfChunksToWrite - 1;
1114 if(numberOfChunksToWrite <= 0) {
1115 // We care closing the file before returning
1117 return self.close(function(err, result) {
1118 callback(err, self);
1123 return callback(null, self);
1128 // Update the position for the gridstore
1129 self.position = self.position + buffer.length;
1130 // We have less data than the chunk size just write it and callback
1131 self.currentChunk.write(buffer);
1132 // We care closing the file before returning
1134 return self.close(function(err, result) {
1135 callback(err, self);
1139 return callback(null, self);
1145 * Creates a mongoDB object representation of this object.
1149 * '_id' : , // {number} id for this file
1150 * 'filename' : , // {string} name for this file
1151 * 'contentType' : , // {string} mime type for this file
1152 * 'length' : , // {number} size of this file?
1153 * 'chunksize' : , // {number} chunk size used by this file
1154 * 'uploadDate' : , // {Date}
1155 * 'aliases' : , // {array of string}
1156 * 'metadata' : , // {string}
1162 var buildMongoObject = function(self, callback) {
1163 // Calcuate the length
1166 'filename': self.filename,
1167 'contentType': self.contentType,
1168 'length': self.position ? self.position : 0,
1169 'chunkSize': self.chunkSize,
1170 'uploadDate': self.uploadDate,
1171 'aliases': self.aliases,
1172 'metadata': self.metadata
1175 var md5Command = {filemd5:self.fileId, root:self.root};
1176 self.db.command(md5Command, function(err, results) {
1177 if(err) return callback(err);
1179 mongoObject.md5 = results.md5;
1180 callback(null, mongoObject);
1185 * Gets the nth chunk of this file.
1188 var nthChunk = function(self, chunkNumber, options, callback) {
1189 if(typeof options == 'function') {
1194 options = options || self.writeConcern;
1195 options.readPreference = self.readPreference;
1196 // Get the nth chunk
1197 self.chunkCollection().findOne({'files_id':self.fileId, 'n':chunkNumber}, options, function(err, chunk) {
1198 if(err) return callback(err);
1200 var finalChunk = chunk == null ? {} : chunk;
1201 callback(null, new Chunk(self, finalChunk, self.writeConcern));
1208 var lastChunkNumber = function(self) {
1209 return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize);
1213 * Deletes all the chunks of this file in the database.
1217 var deleteChunks = function(self, options, callback) {
1218 if(typeof options == 'function') {
1223 options = options || self.writeConcern;
1225 if(self.fileId != null) {
1226 self.chunkCollection().remove({'files_id':self.fileId}, options, function(err, result) {
1227 if(err) return callback(err, false);
1228 callback(null, true);
1231 callback(null, true);
1236 * The collection to be used for holding the files and chunks collection.
1238 * @classconstant DEFAULT_ROOT_COLLECTION
1240 GridStore.DEFAULT_ROOT_COLLECTION = 'fs';
1243 * Default file mime type
1245 * @classconstant DEFAULT_CONTENT_TYPE
1247 GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream';
1250 * Seek mode where the given length is absolute.
1252 * @classconstant IO_SEEK_SET
1254 GridStore.IO_SEEK_SET = 0;
1257 * Seek mode where the given length is an offset to the current read/write head.
1259 * @classconstant IO_SEEK_CUR
1261 GridStore.IO_SEEK_CUR = 1;
1264 * Seek mode where the given length is an offset to the end of the file.
1266 * @classconstant IO_SEEK_END
1268 GridStore.IO_SEEK_END = 2;
1271 * Checks if a file exists in the database.
1275 * @param {Db} db the database to query.
1276 * @param {string} name The name of the file to look for.
1277 * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.
1278 * @param {object} [options=null] Optional settings.
1279 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
1280 * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
1281 * @param {GridStore~resultCallback} [callback] result from exists.
1282 * @return {Promise} returns Promise if no callback passed
1283 * @deprecated Use GridFSBucket API instead
1285 GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) {
1286 var args = Array.prototype.slice.call(arguments, 2);
1287 callback = args.pop();
1288 if(typeof callback != 'function') args.push(callback);
1289 rootCollection = args.length ? args.shift() : null;
1290 options = args.length ? args.shift() : {};
1291 options = options || {};
1293 // Get the promiseLibrary
1294 var promiseLibrary = options.promiseLibrary;
1296 // No promise library selected fall back
1297 if(!promiseLibrary) {
1298 promiseLibrary = typeof global.Promise == 'function' ?
1299 global.Promise : require('es6-promise').Promise;
1302 // We provided a callback leg
1303 if(typeof callback == 'function') return exists(db, fileIdObject, rootCollection, options, callback);
1305 return new promiseLibrary(function(resolve, reject) {
1306 exists(db, fileIdObject, rootCollection, options, function(err, r) {
1307 if(err) return reject(err);
1313 var exists = function(db, fileIdObject, rootCollection, options, callback) {
1314 // Establish read preference
1315 var readPreference = options.readPreference || ReadPreference.PRIMARY;
1317 var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;
1318 db.collection(rootCollectionFinal + ".files", function(err, collection) {
1319 if(err) return callback(err);
1322 var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' )
1323 ? {'filename':fileIdObject}
1324 : {'_id':fileIdObject}; // Attempt to locate file
1326 // We have a specific query
1327 if(fileIdObject != null
1328 && typeof fileIdObject == 'object'
1329 && Object.prototype.toString.call(fileIdObject) != '[object RegExp]') {
1330 query = fileIdObject;
1333 // Check if the entry exists
1334 collection.findOne(query, {readPreference:readPreference}, function(err, item) {
1335 if(err) return callback(err);
1336 callback(null, item == null ? false : true);
1341 define.staticMethod('exist', {callback: true, promise:true});
1344 * Gets the list of files stored in the GridFS.
1348 * @param {Db} db the database to query.
1349 * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.
1350 * @param {object} [options=null] Optional settings.
1351 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
1352 * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
1353 * @param {GridStore~resultCallback} [callback] result from exists.
1354 * @return {Promise} returns Promise if no callback passed
1355 * @deprecated Use GridFSBucket API instead
1357 GridStore.list = function(db, rootCollection, options, callback) {
1358 var args = Array.prototype.slice.call(arguments, 1);
1359 callback = args.pop();
1360 if(typeof callback != 'function') args.push(callback);
1361 rootCollection = args.length ? args.shift() : null;
1362 options = args.length ? args.shift() : {};
1363 options = options || {};
1365 // Get the promiseLibrary
1366 var promiseLibrary = options.promiseLibrary;
1368 // No promise library selected fall back
1369 if(!promiseLibrary) {
1370 promiseLibrary = typeof global.Promise == 'function' ?
1371 global.Promise : require('es6-promise').Promise;
1374 // We provided a callback leg
1375 if(typeof callback == 'function') return list(db, rootCollection, options, callback);
1377 return new promiseLibrary(function(resolve, reject) {
1378 list(db, rootCollection, options, function(err, r) {
1379 if(err) return reject(err);
1385 var list = function(db, rootCollection, options, callback) {
1386 // Ensure we have correct values
1387 if(rootCollection != null && typeof rootCollection == 'object') {
1388 options = rootCollection;
1389 rootCollection = null;
1392 // Establish read preference
1393 var readPreference = options.readPreference || ReadPreference.PRIMARY;
1394 // Check if we are returning by id not filename
1395 var byId = options['id'] != null ? options['id'] : false;
1397 var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;
1399 db.collection((rootCollectionFinal + ".files"), function(err, collection) {
1400 if(err) return callback(err);
1402 collection.find({}, {readPreference:readPreference}, function(err, cursor) {
1403 if(err) return callback(err);
1405 cursor.each(function(err, item) {
1407 items.push(byId ? item._id : item.filename);
1409 callback(err, items);
1416 define.staticMethod('list', {callback: true, promise:true});
1419 * Reads the contents of a file.
1421 * This method has the following signatures
1423 * (db, name, callback)
1424 * (db, name, length, callback)
1425 * (db, name, length, offset, callback)
1426 * (db, name, length, offset, options, callback)
1430 * @param {Db} db the database to query.
1431 * @param {string} name The name of the file.
1432 * @param {number} [length] The size of data to read.
1433 * @param {number} [offset] The offset from the head of the file of which to start reading from.
1434 * @param {object} [options=null] Optional settings.
1435 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
1436 * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
1437 * @param {GridStore~readCallback} [callback] the command callback.
1438 * @return {Promise} returns Promise if no callback passed
1439 * @deprecated Use GridFSBucket API instead
1441 GridStore.read = function(db, name, length, offset, options, callback) {
1442 var args = Array.prototype.slice.call(arguments, 2);
1443 callback = args.pop();
1444 if(typeof callback != 'function') args.push(callback);
1445 length = args.length ? args.shift() : null;
1446 offset = args.length ? args.shift() : null;
1447 options = args.length ? args.shift() : null;
1448 options = options || {};
1450 // Get the promiseLibrary
1451 var promiseLibrary = options ? options.promiseLibrary : null;
1453 // No promise library selected fall back
1454 if(!promiseLibrary) {
1455 promiseLibrary = typeof global.Promise == 'function' ?
1456 global.Promise : require('es6-promise').Promise;
1459 // We provided a callback leg
1460 if(typeof callback == 'function') return readStatic(db, name, length, offset, options, callback);
1462 return new promiseLibrary(function(resolve, reject) {
1463 readStatic(db, name, length, offset, options, function(err, r) {
1464 if(err) return reject(err);
1470 var readStatic = function(db, name, length, offset, options, callback) {
1471 new GridStore(db, name, "r", options).open(function(err, gridStore) {
1472 if(err) return callback(err);
1473 // Make sure we are not reading out of bounds
1474 if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null);
1475 if(length && length > gridStore.length) return callback("length is larger than the size of the file", null);
1476 if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null);
1478 if(offset != null) {
1479 gridStore.seek(offset, function(err, gridStore) {
1480 if(err) return callback(err);
1481 gridStore.read(length, callback);
1484 gridStore.read(length, callback);
1489 define.staticMethod('read', {callback: true, promise:true});
1492 * Read the entire file as a list of strings splitting by the provided separator.
1496 * @param {Db} db the database to query.
1497 * @param {(String|object)} name the name of the file.
1498 * @param {string} [separator] The character to be recognized as the newline separator.
1499 * @param {object} [options=null] Optional settings.
1500 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
1501 * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
1502 * @param {GridStore~readlinesCallback} [callback] the command callback.
1503 * @return {Promise} returns Promise if no callback passed
1504 * @deprecated Use GridFSBucket API instead
1506 GridStore.readlines = function(db, name, separator, options, callback) {
1507 var args = Array.prototype.slice.call(arguments, 2);
1508 callback = args.pop();
1509 if(typeof callback != 'function') args.push(callback);
1510 separator = args.length ? args.shift() : null;
1511 options = args.length ? args.shift() : null;
1512 options = options || {};
1514 // Get the promiseLibrary
1515 var promiseLibrary = options ? options.promiseLibrary : null;
1517 // No promise library selected fall back
1518 if(!promiseLibrary) {
1519 promiseLibrary = typeof global.Promise == 'function' ?
1520 global.Promise : require('es6-promise').Promise;
1523 // We provided a callback leg
1524 if(typeof callback == 'function') return readlinesStatic(db, name, separator, options, callback);
1526 return new promiseLibrary(function(resolve, reject) {
1527 readlinesStatic(db, name, separator, options, function(err, r) {
1528 if(err) return reject(err);
1534 var readlinesStatic = function(db, name, separator, options, callback) {
1535 var finalSeperator = separator == null ? "\n" : separator;
1536 new GridStore(db, name, "r", options).open(function(err, gridStore) {
1537 if(err) return callback(err);
1538 gridStore.readlines(finalSeperator, callback);
1542 define.staticMethod('readlines', {callback: true, promise:true});
1545 * Deletes the chunks and metadata information of a file from GridFS.
1549 * @param {Db} db The database to query.
1550 * @param {(string|array)} names The name/names of the files to delete.
1551 * @param {object} [options=null] Optional settings.
1552 * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
1553 * @param {GridStore~resultCallback} [callback] the command callback.
1554 * @return {Promise} returns Promise if no callback passed
1555 * @deprecated Use GridFSBucket API instead
1557 GridStore.unlink = function(db, names, options, callback) {
1559 var args = Array.prototype.slice.call(arguments, 2);
1560 callback = args.pop();
1561 if(typeof callback != 'function') args.push(callback);
1562 options = args.length ? args.shift() : {};
1563 options = options || {};
1565 // Get the promiseLibrary
1566 var promiseLibrary = options.promiseLibrary;
1568 // No promise library selected fall back
1569 if(!promiseLibrary) {
1570 promiseLibrary = typeof global.Promise == 'function' ?
1571 global.Promise : require('es6-promise').Promise;
1574 // We provided a callback leg
1575 if(typeof callback == 'function') return unlinkStatic(self, db, names, options, callback);
1578 return new promiseLibrary(function(resolve, reject) {
1579 unlinkStatic(self, db, names, options, function(err, r) {
1580 if(err) return reject(err);
1586 var unlinkStatic = function(self, db, names, options, callback) {
1587 // Get the write concern
1588 var writeConcern = _getWriteConcern(db, options);
1591 if(names.constructor == Array) {
1593 for(var i = 0; i < names.length; i++) {
1595 GridStore.unlink(db, names[i], options, function(result) {
1597 callback(null, self);
1602 new GridStore(db, names, "w", options).open(function(err, gridStore) {
1603 if(err) return callback(err);
1604 deleteChunks(gridStore, function(err, result) {
1605 if(err) return callback(err);
1606 gridStore.collection(function(err, collection) {
1607 if(err) return callback(err);
1608 collection.remove({'_id':gridStore.fileId}, writeConcern, function(err, result) {
1609 callback(err, self);
1617 define.staticMethod('unlink', {callback: true, promise:true});
1622 var _writeNormal = function(self, data, close, callback) {
1623 // If we have a buffer write it using the writeBuffer method
1624 if(Buffer.isBuffer(data)) {
1625 return writeBuffer(self, data, close, callback);
1627 return writeBuffer(self, new Buffer(data, 'binary'), close, callback);
1634 var _setWriteConcernHash = function(options) {
1635 var finalOptions = {};
1636 if(options.w != null) finalOptions.w = options.w;
1637 if(options.journal == true) finalOptions.j = options.journal;
1638 if(options.j == true) finalOptions.j = options.j;
1639 if(options.fsync == true) finalOptions.fsync = options.fsync;
1640 if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout;
1641 return finalOptions;
1647 var _getWriteConcern = function(self, options) {
1649 var finalOptions = {w:1};
1650 options = options || {};
1652 // Local options verification
1653 if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') {
1654 finalOptions = _setWriteConcernHash(options);
1655 } else if(options.safe != null && typeof options.safe == 'object') {
1656 finalOptions = _setWriteConcernHash(options.safe);
1657 } else if(typeof options.safe == "boolean") {
1658 finalOptions = {w: (options.safe ? 1 : 0)};
1659 } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') {
1660 finalOptions = _setWriteConcernHash(self.options);
1661 } else if(self.safe && (self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean')) {
1662 finalOptions = _setWriteConcernHash(self.safe);
1663 } else if(typeof self.safe == "boolean") {
1664 finalOptions = {w: (self.safe ? 1 : 0)};
1667 // Ensure we don't have an invalid combination of write concerns
1668 if(finalOptions.w < 1
1669 && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw MongoError.create({message: "No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true", driver:true});
1671 // Return the options
1672 return finalOptions;
1676 * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly)
1679 * @extends external:Duplex
1680 * @return {GridStoreStream} a GridStoreStream instance.
1681 * @deprecated Use GridFSBucket API instead
1683 var GridStoreStream = function(gs) {
1685 // Initialize the duplex stream
1688 // Get the gridstore
1692 this.endCalled = false;
1694 // If we have a seek
1695 this.totalBytesToRead = this.gs.length - this.gs.position;
1696 this.seekPosition = this.gs.position;
1701 inherits(GridStoreStream, Duplex);
1703 GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe;
1706 GridStoreStream.prototype.pipe = function(destination) {
1709 // Only open gridstore if not already open
1710 if(!self.gs.isOpen) {
1711 self.gs.open(function(err) {
1712 if(err) return self.emit('error', err);
1713 self.totalBytesToRead = self.gs.length - self.gs.position;
1714 self._pipe.apply(self, [destination]);
1717 self.totalBytesToRead = self.gs.length - self.gs.position;
1718 self._pipe.apply(self, [destination]);
1725 GridStoreStream.prototype._read = function(n) {
1728 var read = function() {
1730 self.gs.read(length, function(err, buffer) {
1731 if(err && !self.endCalled) return self.emit('error', err);
1734 if(self.endCalled || buffer == null) return self.push(null);
1735 // Remove bytes read
1736 if(buffer.length <= self.totalBytesToRead) {
1737 self.totalBytesToRead = self.totalBytesToRead - buffer.length;
1739 } else if(buffer.length > self.totalBytesToRead) {
1740 self.totalBytesToRead = self.totalBytesToRead - buffer._index;
1741 self.push(buffer.slice(0, buffer._index));
1745 if(self.totalBytesToRead <= 0) {
1746 self.endCalled = true;
1752 var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize;
1753 if(!self.gs.isOpen) {
1754 self.gs.open(function(err, gs) {
1755 self.totalBytesToRead = self.gs.length - self.gs.position;
1756 if(err) return self.emit('error', err);
1764 GridStoreStream.prototype.destroy = function() {
1766 this.endCalled = true;
1771 GridStoreStream.prototype.write = function(chunk, encoding, callback) {
1773 if(self.endCalled) return self.emit('error', MongoError.create({message: 'attempting to write to stream after end called', driver:true}))
1774 // Do we have to open the gridstore
1775 if(!self.gs.isOpen) {
1776 self.gs.open(function() {
1777 self.gs.isOpen = true;
1778 self.gs.write(chunk, function() {
1779 process.nextTick(function() {
1786 self.gs.write(chunk, function() {
1793 GridStoreStream.prototype.end = function(chunk, encoding, callback) {
1795 var args = Array.prototype.slice.call(arguments, 0);
1796 callback = args.pop();
1797 if(typeof callback != 'function') args.push(callback);
1798 chunk = args.length ? args.shift() : null;
1799 encoding = args.length ? args.shift() : null;
1800 self.endCalled = true;
1803 self.gs.write(chunk, function() {
1804 self.gs.close(function() {
1805 if(typeof callback == 'function') callback();
1811 self.gs.close(function() {
1812 if(typeof callback == 'function') callback();
1818 * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.
1819 * @function external:Duplex#read
1820 * @param {number} size Optional argument to specify how much data to read.
1821 * @return {(String | Buffer | null)}
1825 * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
1826 * @function external:Duplex#setEncoding
1827 * @param {string} encoding The encoding to use.
1832 * This method will cause the readable stream to resume emitting data events.
1833 * @function external:Duplex#resume
1838 * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.
1839 * @function external:Duplex#pause
1844 * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
1845 * @function external:Duplex#pipe
1846 * @param {Writable} destination The destination for writing data
1847 * @param {object} [options] Pipe options
1852 * This method will remove the hooks set up for a previous pipe() call.
1853 * @function external:Duplex#unpipe
1854 * @param {Writable} [destination] The destination for writing data
1859 * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.
1860 * @function external:Duplex#unshift
1861 * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue.
1866 * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.)
1867 * @function external:Duplex#wrap
1868 * @param {Stream} stream An "old style" readable stream.
1873 * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.
1874 * @function external:Duplex#write
1875 * @param {(string|Buffer)} chunk The data to write
1876 * @param {string} encoding The encoding, if chunk is a String
1877 * @param {function} callback Callback for when this chunk of data is flushed
1882 * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event.
1883 * @function external:Duplex#end
1884 * @param {(string|Buffer)} chunk The data to write
1885 * @param {string} encoding The encoding, if chunk is a String
1886 * @param {function} callback Callback for when this chunk of data is flushed
1891 * GridStoreStream stream data event, fired for each document in the cursor.
1893 * @event GridStoreStream#data
1898 * GridStoreStream stream end event
1900 * @event GridStoreStream#end
1905 * GridStoreStream stream close event
1907 * @event GridStoreStream#close
1912 * GridStoreStream stream readable event
1914 * @event GridStoreStream#readable
1919 * GridStoreStream stream drain event
1921 * @event GridStoreStream#drain
1926 * GridStoreStream stream finish event
1928 * @event GridStoreStream#finish
1933 * GridStoreStream stream pipe event
1935 * @event GridStoreStream#pipe
1940 * GridStoreStream stream unpipe event
1942 * @event GridStoreStream#unpipe
1947 * GridStoreStream stream error event
1949 * @event GridStoreStream#error
1956 module.exports = GridStore;