grid_store.js 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  1. "use strict";
  2. /**
  3. * @fileOverview GridFS is a tool for MongoDB to store files to the database.
  4. * Because of the restrictions of the object size the database can hold, a
  5. * facility to split a file into several chunks is needed. The {@link GridStore}
  6. * class offers a simplified api to interact with files while managing the
  7. * chunks of split files behind the scenes. More information about GridFS can be
  8. * found <a href="http://www.mongodb.org/display/DOCS/GridFS">here</a>.
  9. *
  10. * @example
  11. * var MongoClient = require('mongodb').MongoClient,
  12. * GridStore = require('mongodb').GridStore,
  13. * ObjectID = require('mongodb').ObjectID,
  14. * test = require('assert');
  15. *
  16. * // Connection url
  17. * var url = 'mongodb://localhost:27017/test';
  18. * // Connect using MongoClient
  19. * MongoClient.connect(url, function(err, db) {
  20. * var gridStore = new GridStore(db, null, "w");
  21. * gridStore.open(function(err, gridStore) {
  22. * gridStore.write("hello world!", function(err, gridStore) {
  23. * gridStore.close(function(err, result) {
  24. *
  25. * // Let's read the file using object Id
  26. * GridStore.read(db, result._id, function(err, data) {
  27. * test.equal('hello world!', data);
  28. * db.close();
  29. * test.done();
  30. * });
  31. * });
  32. * });
  33. * });
  34. * });
  35. */
  36. var Chunk = require('./chunk'),
  37. ObjectID = require('mongodb-core').BSON.ObjectID,
  38. ReadPreference = require('../read_preference'),
  39. Buffer = require('buffer').Buffer,
  40. Collection = require('../collection'),
  41. fs = require('fs'),
  42. timers = require('timers'),
  43. f = require('util').format,
  44. util = require('util'),
  45. Define = require('../metadata'),
  46. MongoError = require('mongodb-core').MongoError,
  47. inherits = util.inherits,
  48. Duplex = require('stream').Duplex || require('readable-stream').Duplex,
  49. shallowClone = require('../utils').shallowClone;
  50. var REFERENCE_BY_FILENAME = 0,
  51. REFERENCE_BY_ID = 1;
  52. /**
  53. * Namespace provided by the mongodb-core and node.js
  54. * @external Duplex
  55. */
  56. /**
  57. * Create a new GridStore instance
  58. *
  59. * Modes
  60. * - **"r"** - read only. This is the default mode.
  61. * - **"w"** - write in truncate mode. Existing data will be overwriten.
  62. *
  63. * @class
  64. * @param {Db} db A database instance to interact with.
  65. * @param {object} [id] optional unique id for this file
  66. * @param {string} [filename] optional filename for this file, no unique constrain on the field
  67. * @param {string} mode set the mode for this file.
  68. * @param {object} [options=null] Optional settings.
  69. * @param {(number|string)} [options.w=null] The write concern.
  70. * @param {number} [options.wtimeout=null] The write concern timeout.
  71. * @param {boolean} [options.j=false] Specify a journal write concern.
  72. * @param {boolean} [options.fsync=false] Specify a file sync write concern.
  73. * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.
  74. * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**.
  75. * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**.
  76. * @param {object} [options.metadata=null] Arbitrary data the user wants to store.
  77. * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
  78. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  79. * @property {number} chunkSize Get the gridstore chunk size.
  80. * @property {number} md5 The md5 checksum for this file.
  81. * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory
  82. * @return {GridStore} a GridStore instance.
  83. */
  84. var GridStore = function GridStore(db, id, filename, mode, options) {
  85. if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options);
  86. var self = this;
  87. this.db = db;
  88. // Handle options
  89. if(typeof options === 'undefined') options = {};
  90. // Handle mode
  91. if(typeof mode === 'undefined') {
  92. mode = filename;
  93. filename = undefined;
  94. } else if(typeof mode == 'object') {
  95. options = mode;
  96. mode = filename;
  97. filename = undefined;
  98. }
  99. if(id instanceof ObjectID) {
  100. this.referenceBy = REFERENCE_BY_ID;
  101. this.fileId = id;
  102. this.filename = filename;
  103. } else if(typeof filename == 'undefined') {
  104. this.referenceBy = REFERENCE_BY_FILENAME;
  105. this.filename = id;
  106. if (mode.indexOf('w') != null) {
  107. this.fileId = new ObjectID();
  108. }
  109. } else {
  110. this.referenceBy = REFERENCE_BY_ID;
  111. this.fileId = id;
  112. this.filename = filename;
  113. }
  114. // Set up the rest
  115. this.mode = mode == null ? "r" : mode;
  116. this.options = options || {};
  117. // Opened
  118. this.isOpen = false;
  119. // Set the root if overridden
  120. this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root'];
  121. this.position = 0;
  122. this.readPreference = this.options.readPreference || db.options.readPreference || ReadPreference.PRIMARY;
  123. this.writeConcern = _getWriteConcern(db, this.options);
  124. // Set default chunk size
  125. this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize'];
  126. // Get the promiseLibrary
  127. var promiseLibrary = this.options.promiseLibrary;
  128. // No promise library selected fall back
  129. if(!promiseLibrary) {
  130. promiseLibrary = typeof global.Promise == 'function' ?
  131. global.Promise : require('es6-promise').Promise;
  132. }
  133. // Set the promiseLibrary
  134. this.promiseLibrary = promiseLibrary;
  135. Object.defineProperty(this, "chunkSize", { enumerable: true
  136. , get: function () {
  137. return this.internalChunkSize;
  138. }
  139. , set: function(value) {
  140. if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) {
  141. this.internalChunkSize = this.internalChunkSize;
  142. } else {
  143. this.internalChunkSize = value;
  144. }
  145. }
  146. });
  147. Object.defineProperty(this, "md5", { enumerable: true
  148. , get: function () {
  149. return this.internalMd5;
  150. }
  151. });
  152. Object.defineProperty(this, "chunkNumber", { enumerable: true
  153. , get: function () {
  154. return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null;
  155. }
  156. });
  157. }
  158. var define = GridStore.define = new Define('Gridstore', GridStore, true);
  159. /**
  160. * The callback format for the Gridstore.open method
  161. * @callback GridStore~openCallback
  162. * @param {MongoError} error An error instance representing the error during the execution.
  163. * @param {GridStore} gridStore The GridStore instance if the open method was successful.
  164. */
  165. /**
  166. * Opens the file from the database and initialize this object. Also creates a
  167. * new one if file does not exist.
  168. *
  169. * @method
  170. * @param {GridStore~openCallback} [callback] this will be called after executing this method
  171. * @return {Promise} returns Promise if no callback passed
  172. */
  173. GridStore.prototype.open = function(callback) {
  174. var self = this;
  175. if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){
  176. throw MongoError.create({message: "Illegal mode " + this.mode, driver:true});
  177. }
  178. // We provided a callback leg
  179. if(typeof callback == 'function') return open(self, callback);
  180. // Return promise
  181. return new self.promiseLibrary(function(resolve, reject) {
  182. open(self, function(err, store) {
  183. if(err) return reject(err);
  184. resolve(store);
  185. })
  186. });
  187. };
  188. var open = function(self, callback) {
  189. // Get the write concern
  190. var writeConcern = _getWriteConcern(self.db, self.options);
  191. // If we are writing we need to ensure we have the right indexes for md5's
  192. if((self.mode == "w" || self.mode == "w+")) {
  193. // Get files collection
  194. var collection = self.collection();
  195. // Put index on filename
  196. collection.ensureIndex([['filename', 1]], writeConcern, function(err, index) {
  197. // Get chunk collection
  198. var chunkCollection = self.chunkCollection();
  199. // Make an unique index for compatibility with mongo-cxx-driver:legacy
  200. var chunkIndexOptions = shallowClone(writeConcern);
  201. chunkIndexOptions.unique = true;
  202. // Ensure index on chunk collection
  203. chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], chunkIndexOptions, function(err, index) {
  204. // Open the connection
  205. _open(self, writeConcern, function(err, r) {
  206. if(err) return callback(err);
  207. self.isOpen = true;
  208. callback(err, r);
  209. });
  210. });
  211. });
  212. } else {
  213. // Open the gridstore
  214. _open(self, writeConcern, function(err, r) {
  215. if(err) return callback(err);
  216. self.isOpen = true;
  217. callback(err, r);
  218. });
  219. }
  220. }
  221. // Push the definition for open
  222. define.classMethod('open', {callback: true, promise:true});
  223. /**
  224. * Verify if the file is at EOF.
  225. *
  226. * @method
  227. * @return {boolean} true if the read/write head is at the end of this file.
  228. */
  229. GridStore.prototype.eof = function() {
  230. return this.position == this.length ? true : false;
  231. }
  232. define.classMethod('eof', {callback: false, promise:false, returns: [Boolean]});
  233. /**
  234. * The callback result format.
  235. * @callback GridStore~resultCallback
  236. * @param {MongoError} error An error instance representing the error during the execution.
  237. * @param {object} result The result from the callback.
  238. */
  239. /**
  240. * Retrieves a single character from this file.
  241. *
  242. * @method
  243. * @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.
  244. * @return {Promise} returns Promise if no callback passed
  245. */
  246. GridStore.prototype.getc = function(callback) {
  247. var self = this;
  248. // We provided a callback leg
  249. if(typeof callback == 'function') return eof(self, callback);
  250. // Return promise
  251. return new self.promiseLibrary(function(resolve, reject) {
  252. eof(self, function(err, r) {
  253. if(err) return reject(err);
  254. resolve(r);
  255. })
  256. });
  257. }
  258. var eof = function(self, callback) {
  259. if(self.eof()) {
  260. callback(null, null);
  261. } else if(self.currentChunk.eof()) {
  262. nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) {
  263. self.currentChunk = chunk;
  264. self.position = self.position + 1;
  265. callback(err, self.currentChunk.getc());
  266. });
  267. } else {
  268. self.position = self.position + 1;
  269. callback(null, self.currentChunk.getc());
  270. }
  271. }
  272. define.classMethod('getc', {callback: true, promise:true});
  273. /**
  274. * Writes a string to the file with a newline character appended at the end if
  275. * the given string does not have one.
  276. *
  277. * @method
  278. * @param {string} string the string to write.
  279. * @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.
  280. * @return {Promise} returns Promise if no callback passed
  281. */
  282. GridStore.prototype.puts = function(string, callback) {
  283. var self = this;
  284. var finalString = string.match(/\n$/) == null ? string + "\n" : string;
  285. // We provided a callback leg
  286. if(typeof callback == 'function') return this.write(finalString, callback);
  287. // Return promise
  288. return new self.promiseLibrary(function(resolve, reject) {
  289. self.write(finalString, function(err, r) {
  290. if(err) return reject(err);
  291. resolve(r);
  292. })
  293. });
  294. }
  295. define.classMethod('puts', {callback: true, promise:true});
  296. /**
  297. * Return a modified Readable stream including a possible transform method.
  298. *
  299. * @method
  300. * @return {GridStoreStream}
  301. */
  302. GridStore.prototype.stream = function() {
  303. return new GridStoreStream(this);
  304. }
  305. define.classMethod('stream', {callback: false, promise:false, returns: [GridStoreStream]});
  306. /**
  307. * Writes some data. This method will work properly only if initialized with mode "w" or "w+".
  308. *
  309. * @method
  310. * @param {(string|Buffer)} data the data to write.
  311. * @param {boolean} [close] closes this file after writing if set to true.
  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. */
  315. GridStore.prototype.write = function write(data, close, callback) {
  316. var self = this;
  317. // We provided a callback leg
  318. if(typeof callback == 'function') return _writeNormal(this, data, close, callback);
  319. // Return promise
  320. return new self.promiseLibrary(function(resolve, reject) {
  321. _writeNormal(self, data, close, function(err, r) {
  322. if(err) return reject(err);
  323. resolve(r);
  324. })
  325. });
  326. }
  327. define.classMethod('write', {callback: true, promise:true});
  328. /**
  329. * Handles the destroy part of a stream
  330. *
  331. * @method
  332. * @result {null}
  333. */
  334. GridStore.prototype.destroy = function destroy() {
  335. // close and do not emit any more events. queued data is not sent.
  336. if(!this.writable) return;
  337. this.readable = false;
  338. if(this.writable) {
  339. this.writable = false;
  340. this._q.length = 0;
  341. this.emit('close');
  342. }
  343. }
  344. define.classMethod('destroy', {callback: false, promise:false});
  345. /**
  346. * Stores a file from the file system to the GridFS database.
  347. *
  348. * @method
  349. * @param {(string|Buffer|FileHandle)} file the file to store.
  350. * @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.
  351. * @return {Promise} returns Promise if no callback passed
  352. */
  353. GridStore.prototype.writeFile = function (file, callback) {
  354. var self = this;
  355. // We provided a callback leg
  356. if(typeof callback == 'function') return writeFile(self, file, callback);
  357. // Return promise
  358. return new self.promiseLibrary(function(resolve, reject) {
  359. writeFile(self, file, function(err, r) {
  360. if(err) return reject(err);
  361. resolve(r);
  362. })
  363. });
  364. };
  365. var writeFile = function(self, file, callback) {
  366. if (typeof file === 'string') {
  367. fs.open(file, 'r', function (err, fd) {
  368. if(err) return callback(err);
  369. self.writeFile(fd, callback);
  370. });
  371. return;
  372. }
  373. self.open(function (err, self) {
  374. if(err) return callback(err, self);
  375. fs.fstat(file, function (err, stats) {
  376. if(err) return callback(err, self);
  377. var offset = 0;
  378. var index = 0;
  379. var numberOfChunksLeft = Math.min(stats.size / self.chunkSize);
  380. // Write a chunk
  381. var writeChunk = function() {
  382. fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) {
  383. if(err) return callback(err, self);
  384. offset = offset + bytesRead;
  385. // Create a new chunk for the data
  386. var chunk = new Chunk(self, {n:index++}, self.writeConcern);
  387. chunk.write(data, function(err, chunk) {
  388. if(err) return callback(err, self);
  389. chunk.save({}, function(err, result) {
  390. if(err) return callback(err, self);
  391. self.position = self.position + data.length;
  392. // Point to current chunk
  393. self.currentChunk = chunk;
  394. if(offset >= stats.size) {
  395. fs.close(file);
  396. self.close(function(err, result) {
  397. if(err) return callback(err, self);
  398. return callback(null, self);
  399. });
  400. } else {
  401. return process.nextTick(writeChunk);
  402. }
  403. });
  404. });
  405. });
  406. }
  407. // Process the first write
  408. process.nextTick(writeChunk);
  409. });
  410. });
  411. }
  412. define.classMethod('writeFile', {callback: true, promise:true});
  413. /**
  414. * Saves this file to the database. This will overwrite the old entry if it
  415. * already exists. This will work properly only if mode was initialized to
  416. * "w" or "w+".
  417. *
  418. * @method
  419. * @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.
  420. * @return {Promise} returns Promise if no callback passed
  421. */
  422. GridStore.prototype.close = function(callback) {
  423. var self = this;
  424. // We provided a callback leg
  425. if(typeof callback == 'function') return close(self, callback);
  426. // Return promise
  427. return new self.promiseLibrary(function(resolve, reject) {
  428. close(self, function(err, r) {
  429. if(err) return reject(err);
  430. resolve(r);
  431. })
  432. });
  433. };
  434. var close = function(self, callback) {
  435. if(self.mode[0] == "w") {
  436. // Set up options
  437. var options = self.writeConcern;
  438. if(self.currentChunk != null && self.currentChunk.position > 0) {
  439. self.currentChunk.save({}, function(err, chunk) {
  440. if(err && typeof callback == 'function') return callback(err);
  441. self.collection(function(err, files) {
  442. if(err && typeof callback == 'function') return callback(err);
  443. // Build the mongo object
  444. if(self.uploadDate != null) {
  445. buildMongoObject(self, function(err, mongoObject) {
  446. if(err) {
  447. if(typeof callback == 'function') return callback(err); else throw err;
  448. }
  449. files.save(mongoObject, options, function(err) {
  450. if(typeof callback == 'function')
  451. callback(err, mongoObject);
  452. });
  453. });
  454. } else {
  455. self.uploadDate = new Date();
  456. buildMongoObject(self, function(err, mongoObject) {
  457. if(err) {
  458. if(typeof callback == 'function') return callback(err); else throw err;
  459. }
  460. files.save(mongoObject, options, function(err) {
  461. if(typeof callback == 'function')
  462. callback(err, mongoObject);
  463. });
  464. });
  465. }
  466. });
  467. });
  468. } else {
  469. self.collection(function(err, files) {
  470. if(err && typeof callback == 'function') return callback(err);
  471. self.uploadDate = new Date();
  472. buildMongoObject(self, function(err, mongoObject) {
  473. if(err) {
  474. if(typeof callback == 'function') return callback(err); else throw err;
  475. }
  476. files.save(mongoObject, options, function(err) {
  477. if(typeof callback == 'function')
  478. callback(err, mongoObject);
  479. });
  480. });
  481. });
  482. }
  483. } else if(self.mode[0] == "r") {
  484. if(typeof callback == 'function')
  485. callback(null, null);
  486. } else {
  487. if(typeof callback == 'function')
  488. callback(MongoError.create({message: f("Illegal mode %s", self.mode), driver:true}));
  489. }
  490. }
  491. define.classMethod('close', {callback: true, promise:true});
  492. /**
  493. * The collection callback format.
  494. * @callback GridStore~collectionCallback
  495. * @param {MongoError} error An error instance representing the error during the execution.
  496. * @param {Collection} collection The collection from the command execution.
  497. */
  498. /**
  499. * Retrieve this file's chunks collection.
  500. *
  501. * @method
  502. * @param {GridStore~collectionCallback} callback the command callback.
  503. * @return {Collection}
  504. */
  505. GridStore.prototype.chunkCollection = function(callback) {
  506. if(typeof callback == 'function')
  507. return this.db.collection((this.root + ".chunks"), callback);
  508. return this.db.collection((this.root + ".chunks"));
  509. };
  510. define.classMethod('chunkCollection', {callback: true, promise:false, returns: [Collection]});
  511. /**
  512. * Deletes all the chunks of this file in the database.
  513. *
  514. * @method
  515. * @param {GridStore~resultCallback} [callback] the command callback.
  516. * @return {Promise} returns Promise if no callback passed
  517. */
  518. GridStore.prototype.unlink = function(callback) {
  519. var self = this;
  520. // We provided a callback leg
  521. if(typeof callback == 'function') return unlink(self, callback);
  522. // Return promise
  523. return new self.promiseLibrary(function(resolve, reject) {
  524. unlink(self, function(err, r) {
  525. if(err) return reject(err);
  526. resolve(r);
  527. })
  528. });
  529. };
  530. var unlink = function(self, callback) {
  531. deleteChunks(self, function(err) {
  532. if(err!==null) {
  533. err.message = "at deleteChunks: " + err.message;
  534. return callback(err);
  535. }
  536. self.collection(function(err, collection) {
  537. if(err!==null) {
  538. err.message = "at collection: " + err.message;
  539. return callback(err);
  540. }
  541. collection.remove({'_id':self.fileId}, self.writeConcern, function(err) {
  542. callback(err, self);
  543. });
  544. });
  545. });
  546. }
  547. define.classMethod('unlink', {callback: true, promise:true});
  548. /**
  549. * Retrieves the file collection associated with this object.
  550. *
  551. * @method
  552. * @param {GridStore~collectionCallback} callback the command callback.
  553. * @return {Collection}
  554. */
  555. GridStore.prototype.collection = function(callback) {
  556. if(typeof callback == 'function')
  557. this.db.collection(this.root + ".files", callback);
  558. return this.db.collection(this.root + ".files");
  559. };
  560. define.classMethod('collection', {callback: true, promise:false, returns: [Collection]});
  561. /**
  562. * The readlines callback format.
  563. * @callback GridStore~readlinesCallback
  564. * @param {MongoError} error An error instance representing the error during the execution.
  565. * @param {string[]} strings The array of strings returned.
  566. */
  567. /**
  568. * Read the entire file as a list of strings splitting by the provided separator.
  569. *
  570. * @method
  571. * @param {string} [separator] The character to be recognized as the newline separator.
  572. * @param {GridStore~readlinesCallback} [callback] the command callback.
  573. * @return {Promise} returns Promise if no callback passed
  574. */
  575. GridStore.prototype.readlines = function(separator, callback) {
  576. var self = this;
  577. var args = Array.prototype.slice.call(arguments, 0);
  578. callback = args.pop();
  579. if(typeof callback != 'function') args.push(callback);
  580. separator = args.length ? args.shift() : "\n";
  581. separator = separator || "\n";
  582. // We provided a callback leg
  583. if(typeof callback == 'function') return readlines(self, separator, callback);
  584. // Return promise
  585. return new self.promiseLibrary(function(resolve, reject) {
  586. readlines(self, separator, function(err, r) {
  587. if(err) return reject(err);
  588. resolve(r);
  589. })
  590. });
  591. };
  592. var readlines = function(self, separator, callback) {
  593. self.read(function(err, data) {
  594. if(err) return callback(err);
  595. var items = data.toString().split(separator);
  596. items = items.length > 0 ? items.splice(0, items.length - 1) : [];
  597. for(var i = 0; i < items.length; i++) {
  598. items[i] = items[i] + separator;
  599. }
  600. callback(null, items);
  601. });
  602. }
  603. define.classMethod('readlines', {callback: true, promise:true});
  604. /**
  605. * Deletes all the chunks of this file in the database if mode was set to "w" or
  606. * "w+" and resets the read/write head to the initial position.
  607. *
  608. * @method
  609. * @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.
  610. * @return {Promise} returns Promise if no callback passed
  611. */
  612. GridStore.prototype.rewind = function(callback) {
  613. var self = this;
  614. // We provided a callback leg
  615. if(typeof callback == 'function') return rewind(self, callback);
  616. // Return promise
  617. return new self.promiseLibrary(function(resolve, reject) {
  618. rewind(self, function(err, r) {
  619. if(err) return reject(err);
  620. resolve(r);
  621. })
  622. });
  623. };
  624. var rewind = function(self, callback) {
  625. if(self.currentChunk.chunkNumber != 0) {
  626. if(self.mode[0] == "w") {
  627. deleteChunks(self, function(err, gridStore) {
  628. if(err) return callback(err);
  629. self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern);
  630. self.position = 0;
  631. callback(null, self);
  632. });
  633. } else {
  634. self.currentChunk(0, function(err, chunk) {
  635. if(err) return callback(err);
  636. self.currentChunk = chunk;
  637. self.currentChunk.rewind();
  638. self.position = 0;
  639. callback(null, self);
  640. });
  641. }
  642. } else {
  643. self.currentChunk.rewind();
  644. self.position = 0;
  645. callback(null, self);
  646. }
  647. }
  648. define.classMethod('rewind', {callback: true, promise:true});
  649. /**
  650. * The read callback format.
  651. * @callback GridStore~readCallback
  652. * @param {MongoError} error An error instance representing the error during the execution.
  653. * @param {Buffer} data The data read from the GridStore object
  654. */
  655. /**
  656. * Retrieves the contents of this file and advances the read/write head. Works with Buffers only.
  657. *
  658. * There are 3 signatures for this method:
  659. *
  660. * (callback)
  661. * (length, callback)
  662. * (length, buffer, callback)
  663. *
  664. * @method
  665. * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified.
  666. * @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.
  667. * @param {GridStore~readCallback} [callback] the command callback.
  668. * @return {Promise} returns Promise if no callback passed
  669. */
  670. GridStore.prototype.read = function(length, buffer, callback) {
  671. var self = this;
  672. var args = Array.prototype.slice.call(arguments, 0);
  673. callback = args.pop();
  674. if(typeof callback != 'function') args.push(callback);
  675. length = args.length ? args.shift() : null;
  676. buffer = args.length ? args.shift() : null;
  677. // We provided a callback leg
  678. if(typeof callback == 'function') return read(self, length, buffer, callback);
  679. // Return promise
  680. return new self.promiseLibrary(function(resolve, reject) {
  681. read(self, length, buffer, function(err, r) {
  682. if(err) return reject(err);
  683. resolve(r);
  684. })
  685. });
  686. }
  687. var read = function(self, length, buffer, callback) {
  688. // The data is a c-terminated string and thus the length - 1
  689. var finalLength = length == null ? self.length - self.position : length;
  690. var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer;
  691. // Add a index to buffer to keep track of writing position or apply current index
  692. finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0;
  693. if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) {
  694. var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index);
  695. // Copy content to final buffer
  696. slice.copy(finalBuffer, finalBuffer._index);
  697. // Update internal position
  698. self.position = self.position + finalBuffer.length;
  699. // Check if we don't have a file at all
  700. if(finalLength == 0 && finalBuffer.length == 0) return callback(MongoError.create({message: "File does not exist", driver:true}), null);
  701. // Else return data
  702. return callback(null, finalBuffer);
  703. }
  704. // Read the next chunk
  705. var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position);
  706. // Copy content to final buffer
  707. slice.copy(finalBuffer, finalBuffer._index);
  708. // Update index position
  709. finalBuffer._index += slice.length;
  710. // Load next chunk and read more
  711. nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) {
  712. if(err) return callback(err);
  713. if(chunk.length() > 0) {
  714. self.currentChunk = chunk;
  715. self.read(length, finalBuffer, callback);
  716. } else {
  717. if(finalBuffer._index > 0) {
  718. callback(null, finalBuffer)
  719. } else {
  720. callback(MongoError.create({message: "no chunks found for file, possibly corrupt", driver:true}), null);
  721. }
  722. }
  723. });
  724. }
  725. define.classMethod('read', {callback: true, promise:true});
  726. /**
  727. * The tell callback format.
  728. * @callback GridStore~tellCallback
  729. * @param {MongoError} error An error instance representing the error during the execution.
  730. * @param {number} position The current read position in the GridStore.
  731. */
  732. /**
  733. * Retrieves the position of the read/write head of this file.
  734. *
  735. * @method
  736. * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified.
  737. * @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.
  738. * @param {GridStore~tellCallback} [callback] the command callback.
  739. * @return {Promise} returns Promise if no callback passed
  740. */
  741. GridStore.prototype.tell = function(callback) {
  742. var self = this;
  743. // We provided a callback leg
  744. if(typeof callback == 'function') return callback(null, this.position);
  745. // Return promise
  746. return new self.promiseLibrary(function(resolve, reject) {
  747. resolve(self.position);
  748. });
  749. };
  750. define.classMethod('tell', {callback: true, promise:true});
  751. /**
  752. * The tell callback format.
  753. * @callback GridStore~gridStoreCallback
  754. * @param {MongoError} error An error instance representing the error during the execution.
  755. * @param {GridStore} gridStore The gridStore.
  756. */
  757. /**
  758. * Moves the read/write head to a new location.
  759. *
  760. * There are 3 signatures for this method
  761. *
  762. * Seek Location Modes
  763. * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file.
  764. * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file.
  765. * - **GridStore.IO_SEEK_END**, set the position from the end of the file.
  766. *
  767. * @method
  768. * @param {number} [position] the position to seek to
  769. * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes.
  770. * @param {GridStore~gridStoreCallback} [callback] the command callback.
  771. * @return {Promise} returns Promise if no callback passed
  772. */
  773. GridStore.prototype.seek = function(position, seekLocation, callback) {
  774. var self = this;
  775. var args = Array.prototype.slice.call(arguments, 1);
  776. callback = args.pop();
  777. if(typeof callback != 'function') args.push(callback);
  778. seekLocation = args.length ? args.shift() : null;
  779. // We provided a callback leg
  780. if(typeof callback == 'function') return seek(self, position, seekLocation, callback);
  781. // Return promise
  782. return new self.promiseLibrary(function(resolve, reject) {
  783. seek(self, position, seekLocation, function(err, r) {
  784. if(err) return reject(err);
  785. resolve(r);
  786. })
  787. });
  788. }
  789. var seek = function(self, position, seekLocation, callback) {
  790. // Seek only supports read mode
  791. if(self.mode != 'r') {
  792. return callback(MongoError.create({message: "seek is only supported for mode r", driver:true}))
  793. }
  794. var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation;
  795. var finalPosition = position;
  796. var targetPosition = 0;
  797. // Calculate the position
  798. if(seekLocationFinal == GridStore.IO_SEEK_CUR) {
  799. targetPosition = self.position + finalPosition;
  800. } else if(seekLocationFinal == GridStore.IO_SEEK_END) {
  801. targetPosition = self.length + finalPosition;
  802. } else {
  803. targetPosition = finalPosition;
  804. }
  805. // Get the chunk
  806. var newChunkNumber = Math.floor(targetPosition/self.chunkSize);
  807. var seekChunk = function() {
  808. nthChunk(self, newChunkNumber, function(err, chunk) {
  809. if(err) return callback(err, null);
  810. if(chunk == null) return callback(new Error('no chunk found'));
  811. // Set the current chunk
  812. self.currentChunk = chunk;
  813. self.position = targetPosition;
  814. self.currentChunk.position = (self.position % self.chunkSize);
  815. callback(err, self);
  816. });
  817. };
  818. seekChunk();
  819. }
  820. define.classMethod('seek', {callback: true, promise:true});
  821. /**
  822. * @ignore
  823. */
  824. var _open = function(self, options, callback) {
  825. var collection = self.collection();
  826. // Create the query
  827. var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename};
  828. query = null == self.fileId && self.filename == null ? null : query;
  829. options.readPreference = self.readPreference;
  830. // Fetch the chunks
  831. if(query != null) {
  832. collection.findOne(query, options, function(err, doc) {
  833. if(err) return error(err);
  834. // Check if the collection for the files exists otherwise prepare the new one
  835. if(doc != null) {
  836. self.fileId = doc._id;
  837. // Prefer a new filename over the existing one if this is a write
  838. self.filename = ((self.mode == 'r') || (self.filename == undefined)) ? doc.filename : self.filename;
  839. self.contentType = doc.contentType;
  840. self.internalChunkSize = doc.chunkSize;
  841. self.uploadDate = doc.uploadDate;
  842. self.aliases = doc.aliases;
  843. self.length = doc.length;
  844. self.metadata = doc.metadata;
  845. self.internalMd5 = doc.md5;
  846. } else if (self.mode != 'r') {
  847. self.fileId = self.fileId == null ? new ObjectID() : self.fileId;
  848. self.contentType = GridStore.DEFAULT_CONTENT_TYPE;
  849. self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize;
  850. self.length = 0;
  851. } else {
  852. self.length = 0;
  853. var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId;
  854. 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);
  855. }
  856. // Process the mode of the object
  857. if(self.mode == "r") {
  858. nthChunk(self, 0, options, function(err, chunk) {
  859. if(err) return error(err);
  860. self.currentChunk = chunk;
  861. self.position = 0;
  862. callback(null, self);
  863. });
  864. } else if(self.mode == "w" && doc) {
  865. // Delete any existing chunks
  866. deleteChunks(self, options, function(err, result) {
  867. if(err) return error(err);
  868. self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern);
  869. self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type'];
  870. self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];
  871. self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
  872. self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
  873. self.position = 0;
  874. callback(null, self);
  875. });
  876. } else if(self.mode == "w") {
  877. self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern);
  878. self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type'];
  879. self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];
  880. self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
  881. self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
  882. self.position = 0;
  883. callback(null, self);
  884. } else if(self.mode == "w+") {
  885. nthChunk(self, lastChunkNumber(self), options, function(err, chunk) {
  886. if(err) return error(err);
  887. // Set the current chunk
  888. self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk;
  889. self.currentChunk.position = self.currentChunk.data.length();
  890. self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
  891. self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
  892. self.position = self.length;
  893. callback(null, self);
  894. });
  895. }
  896. });
  897. } else {
  898. // Write only mode
  899. self.fileId = null == self.fileId ? new ObjectID() : self.fileId;
  900. self.contentType = GridStore.DEFAULT_CONTENT_TYPE;
  901. self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize;
  902. self.length = 0;
  903. var collection2 = self.chunkCollection();
  904. // No file exists set up write mode
  905. if(self.mode == "w") {
  906. // Delete any existing chunks
  907. deleteChunks(self, options, function(err, result) {
  908. if(err) return error(err);
  909. self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern);
  910. self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type'];
  911. self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size'];
  912. self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
  913. self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
  914. self.position = 0;
  915. callback(null, self);
  916. });
  917. } else if(self.mode == "w+") {
  918. nthChunk(self, lastChunkNumber(self), options, function(err, chunk) {
  919. if(err) return error(err);
  920. // Set the current chunk
  921. self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk;
  922. self.currentChunk.position = self.currentChunk.data.length();
  923. self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata'];
  924. self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases'];
  925. self.position = self.length;
  926. callback(null, self);
  927. });
  928. }
  929. }
  930. // only pass error to callback once
  931. function error (err) {
  932. if(error.err) return;
  933. callback(error.err = err);
  934. }
  935. };
  936. /**
  937. * @ignore
  938. */
  939. var writeBuffer = function(self, buffer, close, callback) {
  940. if(typeof close === "function") { callback = close; close = null; }
  941. var finalClose = typeof close == 'boolean' ? close : false;
  942. if(self.mode != "w") {
  943. 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);
  944. } else {
  945. if(self.currentChunk.position + buffer.length >= self.chunkSize) {
  946. // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left
  947. // to a new chunk (recursively)
  948. var previousChunkNumber = self.currentChunk.chunkNumber;
  949. var leftOverDataSize = self.chunkSize - self.currentChunk.position;
  950. var firstChunkData = buffer.slice(0, leftOverDataSize);
  951. var leftOverData = buffer.slice(leftOverDataSize);
  952. // A list of chunks to write out
  953. var chunksToWrite = [self.currentChunk.write(firstChunkData)];
  954. // If we have more data left than the chunk size let's keep writing new chunks
  955. while(leftOverData.length >= self.chunkSize) {
  956. // Create a new chunk and write to it
  957. var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern);
  958. var firstChunkData = leftOverData.slice(0, self.chunkSize);
  959. leftOverData = leftOverData.slice(self.chunkSize);
  960. // Update chunk number
  961. previousChunkNumber = previousChunkNumber + 1;
  962. // Write data
  963. newChunk.write(firstChunkData);
  964. // Push chunk to save list
  965. chunksToWrite.push(newChunk);
  966. }
  967. // Set current chunk with remaining data
  968. self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern);
  969. // If we have left over data write it
  970. if(leftOverData.length > 0) self.currentChunk.write(leftOverData);
  971. // Update the position for the gridstore
  972. self.position = self.position + buffer.length;
  973. // Total number of chunks to write
  974. var numberOfChunksToWrite = chunksToWrite.length;
  975. for(var i = 0; i < chunksToWrite.length; i++) {
  976. chunksToWrite[i].save({}, function(err, result) {
  977. if(err) return callback(err);
  978. numberOfChunksToWrite = numberOfChunksToWrite - 1;
  979. if(numberOfChunksToWrite <= 0) {
  980. // We care closing the file before returning
  981. if(finalClose) {
  982. return self.close(function(err, result) {
  983. callback(err, self);
  984. });
  985. }
  986. // Return normally
  987. return callback(null, self);
  988. }
  989. });
  990. }
  991. } else {
  992. // Update the position for the gridstore
  993. self.position = self.position + buffer.length;
  994. // We have less data than the chunk size just write it and callback
  995. self.currentChunk.write(buffer);
  996. // We care closing the file before returning
  997. if(finalClose) {
  998. return self.close(function(err, result) {
  999. callback(err, self);
  1000. });
  1001. }
  1002. // Return normally
  1003. return callback(null, self);
  1004. }
  1005. }
  1006. };
  1007. /**
  1008. * Creates a mongoDB object representation of this object.
  1009. *
  1010. * <pre><code>
  1011. * {
  1012. * '_id' : , // {number} id for this file
  1013. * 'filename' : , // {string} name for this file
  1014. * 'contentType' : , // {string} mime type for this file
  1015. * 'length' : , // {number} size of this file?
  1016. * 'chunksize' : , // {number} chunk size used by this file
  1017. * 'uploadDate' : , // {Date}
  1018. * 'aliases' : , // {array of string}
  1019. * 'metadata' : , // {string}
  1020. * }
  1021. * </code></pre>
  1022. *
  1023. * @ignore
  1024. */
  1025. var buildMongoObject = function(self, callback) {
  1026. // Calcuate the length
  1027. var mongoObject = {
  1028. '_id': self.fileId,
  1029. 'filename': self.filename,
  1030. 'contentType': self.contentType,
  1031. 'length': self.position ? self.position : 0,
  1032. 'chunkSize': self.chunkSize,
  1033. 'uploadDate': self.uploadDate,
  1034. 'aliases': self.aliases,
  1035. 'metadata': self.metadata
  1036. };
  1037. var md5Command = {filemd5:self.fileId, root:self.root};
  1038. self.db.command(md5Command, function(err, results) {
  1039. if(err) return callback(err);
  1040. mongoObject.md5 = results.md5;
  1041. callback(null, mongoObject);
  1042. });
  1043. };
  1044. /**
  1045. * Gets the nth chunk of this file.
  1046. * @ignore
  1047. */
  1048. var nthChunk = function(self, chunkNumber, options, callback) {
  1049. if(typeof options == 'function') {
  1050. callback = options;
  1051. options = {};
  1052. }
  1053. options = options || self.writeConcern;
  1054. options.readPreference = self.readPreference;
  1055. // Get the nth chunk
  1056. self.chunkCollection().findOne({'files_id':self.fileId, 'n':chunkNumber}, options, function(err, chunk) {
  1057. if(err) return callback(err);
  1058. var finalChunk = chunk == null ? {} : chunk;
  1059. callback(null, new Chunk(self, finalChunk, self.writeConcern));
  1060. });
  1061. };
  1062. /**
  1063. * @ignore
  1064. */
  1065. var lastChunkNumber = function(self) {
  1066. return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize);
  1067. };
  1068. /**
  1069. * Deletes all the chunks of this file in the database.
  1070. *
  1071. * @ignore
  1072. */
  1073. var deleteChunks = function(self, options, callback) {
  1074. if(typeof options == 'function') {
  1075. callback = options;
  1076. options = {};
  1077. }
  1078. options = options || self.writeConcern;
  1079. if(self.fileId != null) {
  1080. self.chunkCollection().remove({'files_id':self.fileId}, options, function(err, result) {
  1081. if(err) return callback(err, false);
  1082. callback(null, true);
  1083. });
  1084. } else {
  1085. callback(null, true);
  1086. }
  1087. };
  1088. /**
  1089. * The collection to be used for holding the files and chunks collection.
  1090. *
  1091. * @classconstant DEFAULT_ROOT_COLLECTION
  1092. **/
  1093. GridStore.DEFAULT_ROOT_COLLECTION = 'fs';
  1094. /**
  1095. * Default file mime type
  1096. *
  1097. * @classconstant DEFAULT_CONTENT_TYPE
  1098. **/
  1099. GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream';
  1100. /**
  1101. * Seek mode where the given length is absolute.
  1102. *
  1103. * @classconstant IO_SEEK_SET
  1104. **/
  1105. GridStore.IO_SEEK_SET = 0;
  1106. /**
  1107. * Seek mode where the given length is an offset to the current read/write head.
  1108. *
  1109. * @classconstant IO_SEEK_CUR
  1110. **/
  1111. GridStore.IO_SEEK_CUR = 1;
  1112. /**
  1113. * Seek mode where the given length is an offset to the end of the file.
  1114. *
  1115. * @classconstant IO_SEEK_END
  1116. **/
  1117. GridStore.IO_SEEK_END = 2;
  1118. /**
  1119. * Checks if a file exists in the database.
  1120. *
  1121. * @method
  1122. * @static
  1123. * @param {Db} db the database to query.
  1124. * @param {string} name The name of the file to look for.
  1125. * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.
  1126. * @param {object} [options=null] Optional settings.
  1127. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1128. * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
  1129. * @param {GridStore~resultCallback} [callback] result from exists.
  1130. * @return {Promise} returns Promise if no callback passed
  1131. */
  1132. GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) {
  1133. var args = Array.prototype.slice.call(arguments, 2);
  1134. callback = args.pop();
  1135. if(typeof callback != 'function') args.push(callback);
  1136. rootCollection = args.length ? args.shift() : null;
  1137. options = args.length ? args.shift() : {};
  1138. options = options || {};
  1139. // Get the promiseLibrary
  1140. var promiseLibrary = options.promiseLibrary;
  1141. // No promise library selected fall back
  1142. if(!promiseLibrary) {
  1143. promiseLibrary = typeof global.Promise == 'function' ?
  1144. global.Promise : require('es6-promise').Promise;
  1145. }
  1146. // We provided a callback leg
  1147. if(typeof callback == 'function') return exists(db, fileIdObject, rootCollection, options, callback);
  1148. // Return promise
  1149. return new promiseLibrary(function(resolve, reject) {
  1150. exists(db, fileIdObject, rootCollection, options, function(err, r) {
  1151. if(err) return reject(err);
  1152. resolve(r);
  1153. })
  1154. });
  1155. };
  1156. var exists = function(db, fileIdObject, rootCollection, options, callback) {
  1157. // Establish read preference
  1158. var readPreference = options.readPreference || ReadPreference.PRIMARY;
  1159. // Fetch collection
  1160. var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;
  1161. db.collection(rootCollectionFinal + ".files", function(err, collection) {
  1162. if(err) return callback(err);
  1163. // Build query
  1164. var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' )
  1165. ? {'filename':fileIdObject}
  1166. : {'_id':fileIdObject}; // Attempt to locate file
  1167. // We have a specific query
  1168. if(fileIdObject != null
  1169. && typeof fileIdObject == 'object'
  1170. && Object.prototype.toString.call(fileIdObject) != '[object RegExp]') {
  1171. query = fileIdObject;
  1172. }
  1173. // Check if the entry exists
  1174. collection.findOne(query, {readPreference:readPreference}, function(err, item) {
  1175. if(err) return callback(err);
  1176. callback(null, item == null ? false : true);
  1177. });
  1178. });
  1179. }
  1180. define.staticMethod('exist', {callback: true, promise:true});
  1181. /**
  1182. * Gets the list of files stored in the GridFS.
  1183. *
  1184. * @method
  1185. * @static
  1186. * @param {Db} db the database to query.
  1187. * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**.
  1188. * @param {object} [options=null] Optional settings.
  1189. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1190. * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
  1191. * @param {GridStore~resultCallback} [callback] result from exists.
  1192. * @return {Promise} returns Promise if no callback passed
  1193. */
  1194. GridStore.list = function(db, rootCollection, options, callback) {
  1195. var args = Array.prototype.slice.call(arguments, 1);
  1196. callback = args.pop();
  1197. if(typeof callback != 'function') args.push(callback);
  1198. rootCollection = args.length ? args.shift() : null;
  1199. options = args.length ? args.shift() : {};
  1200. options = options || {};
  1201. // Get the promiseLibrary
  1202. var promiseLibrary = options.promiseLibrary;
  1203. // No promise library selected fall back
  1204. if(!promiseLibrary) {
  1205. promiseLibrary = typeof global.Promise == 'function' ?
  1206. global.Promise : require('es6-promise').Promise;
  1207. }
  1208. // We provided a callback leg
  1209. if(typeof callback == 'function') return list(db, rootCollection, options, callback);
  1210. // Return promise
  1211. return new promiseLibrary(function(resolve, reject) {
  1212. list(db, rootCollection, options, function(err, r) {
  1213. if(err) return reject(err);
  1214. resolve(r);
  1215. })
  1216. });
  1217. };
  1218. var list = function(db, rootCollection, options, callback) {
  1219. // Ensure we have correct values
  1220. if(rootCollection != null && typeof rootCollection == 'object') {
  1221. options = rootCollection;
  1222. rootCollection = null;
  1223. }
  1224. // Establish read preference
  1225. var readPreference = options.readPreference || ReadPreference.PRIMARY;
  1226. // Check if we are returning by id not filename
  1227. var byId = options['id'] != null ? options['id'] : false;
  1228. // Fetch item
  1229. var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION;
  1230. var items = [];
  1231. db.collection((rootCollectionFinal + ".files"), function(err, collection) {
  1232. if(err) return callback(err);
  1233. collection.find({}, {readPreference:readPreference}, function(err, cursor) {
  1234. if(err) return callback(err);
  1235. cursor.each(function(err, item) {
  1236. if(item != null) {
  1237. items.push(byId ? item._id : item.filename);
  1238. } else {
  1239. callback(err, items);
  1240. }
  1241. });
  1242. });
  1243. });
  1244. }
  1245. define.staticMethod('list', {callback: true, promise:true});
  1246. /**
  1247. * Reads the contents of a file.
  1248. *
  1249. * This method has the following signatures
  1250. *
  1251. * (db, name, callback)
  1252. * (db, name, length, callback)
  1253. * (db, name, length, offset, callback)
  1254. * (db, name, length, offset, options, callback)
  1255. *
  1256. * @method
  1257. * @static
  1258. * @param {Db} db the database to query.
  1259. * @param {string} name The name of the file.
  1260. * @param {number} [length] The size of data to read.
  1261. * @param {number} [offset] The offset from the head of the file of which to start reading from.
  1262. * @param {object} [options=null] Optional settings.
  1263. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1264. * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
  1265. * @param {GridStore~readCallback} [callback] the command callback.
  1266. * @return {Promise} returns Promise if no callback passed
  1267. */
  1268. GridStore.read = function(db, name, length, offset, options, callback) {
  1269. var args = Array.prototype.slice.call(arguments, 2);
  1270. callback = args.pop();
  1271. if(typeof callback != 'function') args.push(callback);
  1272. length = args.length ? args.shift() : null;
  1273. offset = args.length ? args.shift() : null;
  1274. options = args.length ? args.shift() : null;
  1275. options = options || {};
  1276. // Get the promiseLibrary
  1277. var promiseLibrary = options ? options.promiseLibrary : null;
  1278. // No promise library selected fall back
  1279. if(!promiseLibrary) {
  1280. promiseLibrary = typeof global.Promise == 'function' ?
  1281. global.Promise : require('es6-promise').Promise;
  1282. }
  1283. // We provided a callback leg
  1284. if(typeof callback == 'function') return readStatic(db, name, length, offset, options, callback);
  1285. // Return promise
  1286. return new promiseLibrary(function(resolve, reject) {
  1287. readStatic(db, name, length, offset, options, function(err, r) {
  1288. if(err) return reject(err);
  1289. resolve(r);
  1290. })
  1291. });
  1292. };
  1293. var readStatic = function(db, name, length, offset, options, callback) {
  1294. new GridStore(db, name, "r", options).open(function(err, gridStore) {
  1295. if(err) return callback(err);
  1296. // Make sure we are not reading out of bounds
  1297. if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null);
  1298. if(length && length > gridStore.length) return callback("length is larger than the size of the file", null);
  1299. if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null);
  1300. if(offset != null) {
  1301. gridStore.seek(offset, function(err, gridStore) {
  1302. if(err) return callback(err);
  1303. gridStore.read(length, callback);
  1304. });
  1305. } else {
  1306. gridStore.read(length, callback);
  1307. }
  1308. });
  1309. }
  1310. define.staticMethod('read', {callback: true, promise:true});
  1311. /**
  1312. * Read the entire file as a list of strings splitting by the provided separator.
  1313. *
  1314. * @method
  1315. * @static
  1316. * @param {Db} db the database to query.
  1317. * @param {(String|object)} name the name of the file.
  1318. * @param {string} [separator] The character to be recognized as the newline separator.
  1319. * @param {object} [options=null] Optional settings.
  1320. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1321. * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
  1322. * @param {GridStore~readlinesCallback} [callback] the command callback.
  1323. * @return {Promise} returns Promise if no callback passed
  1324. */
  1325. GridStore.readlines = function(db, name, separator, options, callback) {
  1326. var args = Array.prototype.slice.call(arguments, 2);
  1327. callback = args.pop();
  1328. if(typeof callback != 'function') args.push(callback);
  1329. separator = args.length ? args.shift() : null;
  1330. options = args.length ? args.shift() : null;
  1331. options = options || {};
  1332. // Get the promiseLibrary
  1333. var promiseLibrary = options ? options.promiseLibrary : null;
  1334. // No promise library selected fall back
  1335. if(!promiseLibrary) {
  1336. promiseLibrary = typeof global.Promise == 'function' ?
  1337. global.Promise : require('es6-promise').Promise;
  1338. }
  1339. // We provided a callback leg
  1340. if(typeof callback == 'function') return readlinesStatic(db, name, separator, options, callback);
  1341. // Return promise
  1342. return new promiseLibrary(function(resolve, reject) {
  1343. readlinesStatic(db, name, separator, options, function(err, r) {
  1344. if(err) return reject(err);
  1345. resolve(r);
  1346. })
  1347. });
  1348. };
  1349. var readlinesStatic = function(db, name, separator, options, callback) {
  1350. var finalSeperator = separator == null ? "\n" : separator;
  1351. new GridStore(db, name, "r", options).open(function(err, gridStore) {
  1352. if(err) return callback(err);
  1353. gridStore.readlines(finalSeperator, callback);
  1354. });
  1355. }
  1356. define.staticMethod('readlines', {callback: true, promise:true});
  1357. /**
  1358. * Deletes the chunks and metadata information of a file from GridFS.
  1359. *
  1360. * @method
  1361. * @static
  1362. * @param {Db} db The database to query.
  1363. * @param {(string|array)} names The name/names of the files to delete.
  1364. * @param {object} [options=null] Optional settings.
  1365. * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
  1366. * @param {GridStore~resultCallback} [callback] the command callback.
  1367. * @return {Promise} returns Promise if no callback passed
  1368. */
  1369. GridStore.unlink = function(db, names, options, callback) {
  1370. var self = this;
  1371. var args = Array.prototype.slice.call(arguments, 2);
  1372. callback = args.pop();
  1373. if(typeof callback != 'function') args.push(callback);
  1374. options = args.length ? args.shift() : {};
  1375. options = options || {};
  1376. // Get the promiseLibrary
  1377. var promiseLibrary = options.promiseLibrary;
  1378. // No promise library selected fall back
  1379. if(!promiseLibrary) {
  1380. promiseLibrary = typeof global.Promise == 'function' ?
  1381. global.Promise : require('es6-promise').Promise;
  1382. }
  1383. // We provided a callback leg
  1384. if(typeof callback == 'function') return unlinkStatic(self, db, names, options, callback);
  1385. // Return promise
  1386. return new promiseLibrary(function(resolve, reject) {
  1387. unlinkStatic(self, db, names, options, function(err, r) {
  1388. if(err) return reject(err);
  1389. resolve(r);
  1390. })
  1391. });
  1392. };
  1393. var unlinkStatic = function(self, db, names, options, callback) {
  1394. // Get the write concern
  1395. var writeConcern = _getWriteConcern(db, options);
  1396. // List of names
  1397. if(names.constructor == Array) {
  1398. var tc = 0;
  1399. for(var i = 0; i < names.length; i++) {
  1400. ++tc;
  1401. GridStore.unlink(db, names[i], options, function(result) {
  1402. if(--tc == 0) {
  1403. callback(null, self);
  1404. }
  1405. });
  1406. }
  1407. } else {
  1408. new GridStore(db, names, "w", options).open(function(err, gridStore) {
  1409. if(err) return callback(err);
  1410. deleteChunks(gridStore, function(err, result) {
  1411. if(err) return callback(err);
  1412. gridStore.collection(function(err, collection) {
  1413. if(err) return callback(err);
  1414. collection.remove({'_id':gridStore.fileId}, writeConcern, function(err, result) {
  1415. callback(err, self);
  1416. });
  1417. });
  1418. });
  1419. });
  1420. }
  1421. }
  1422. define.staticMethod('unlink', {callback: true, promise:true});
  1423. /**
  1424. * @ignore
  1425. */
  1426. var _writeNormal = function(self, data, close, callback) {
  1427. // If we have a buffer write it using the writeBuffer method
  1428. if(Buffer.isBuffer(data)) {
  1429. return writeBuffer(self, data, close, callback);
  1430. } else {
  1431. return writeBuffer(self, new Buffer(data, 'binary'), close, callback);
  1432. }
  1433. }
  1434. /**
  1435. * @ignore
  1436. */
  1437. var _setWriteConcernHash = function(options) {
  1438. var finalOptions = {};
  1439. if(options.w != null) finalOptions.w = options.w;
  1440. if(options.journal == true) finalOptions.j = options.journal;
  1441. if(options.j == true) finalOptions.j = options.j;
  1442. if(options.fsync == true) finalOptions.fsync = options.fsync;
  1443. if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout;
  1444. return finalOptions;
  1445. }
  1446. /**
  1447. * @ignore
  1448. */
  1449. var _getWriteConcern = function(self, options) {
  1450. // Final options
  1451. var finalOptions = {w:1};
  1452. options = options || {};
  1453. // Local options verification
  1454. if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') {
  1455. finalOptions = _setWriteConcernHash(options);
  1456. } else if(options.safe != null && typeof options.safe == 'object') {
  1457. finalOptions = _setWriteConcernHash(options.safe);
  1458. } else if(typeof options.safe == "boolean") {
  1459. finalOptions = {w: (options.safe ? 1 : 0)};
  1460. } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') {
  1461. finalOptions = _setWriteConcernHash(self.options);
  1462. } else if(self.safe && (self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean')) {
  1463. finalOptions = _setWriteConcernHash(self.safe);
  1464. } else if(typeof self.safe == "boolean") {
  1465. finalOptions = {w: (self.safe ? 1 : 0)};
  1466. }
  1467. // Ensure we don't have an invalid combination of write concerns
  1468. if(finalOptions.w < 1
  1469. && (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});
  1470. // Return the options
  1471. return finalOptions;
  1472. }
  1473. /**
  1474. * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly)
  1475. *
  1476. * @class
  1477. * @extends external:Duplex
  1478. * @return {GridStoreStream} a GridStoreStream instance.
  1479. */
  1480. var GridStoreStream = function(gs) {
  1481. var self = this;
  1482. // Initialize the duplex stream
  1483. Duplex.call(this);
  1484. // Get the gridstore
  1485. this.gs = gs;
  1486. // End called
  1487. this.endCalled = false;
  1488. // If we have a seek
  1489. this.totalBytesToRead = this.gs.length - this.gs.position;
  1490. this.seekPosition = this.gs.position;
  1491. }
  1492. //
  1493. // Inherit duplex
  1494. inherits(GridStoreStream, Duplex);
  1495. GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe;
  1496. // Set up override
  1497. GridStoreStream.prototype.pipe = function(destination) {
  1498. var self = this;
  1499. // Only open gridstore if not already open
  1500. if(!self.gs.isOpen) {
  1501. self.gs.open(function(err) {
  1502. if(err) return self.emit('error', err);
  1503. self.totalBytesToRead = self.gs.length - self.gs.position;
  1504. self._pipe.apply(self, [destination]);
  1505. });
  1506. } else {
  1507. self.totalBytesToRead = self.gs.length - self.gs.position;
  1508. self._pipe.apply(self, [destination]);
  1509. }
  1510. }
  1511. // Called by stream
  1512. GridStoreStream.prototype._read = function(n) {
  1513. var self = this;
  1514. var read = function() {
  1515. // Read data
  1516. self.gs.read(length, function(err, buffer) {
  1517. if(err && !self.endCalled) return self.emit('error', err);
  1518. // Stream is closed
  1519. if(self.endCalled || buffer == null) return self.push(null);
  1520. // Remove bytes read
  1521. if(buffer.length <= self.totalBytesToRead) {
  1522. self.totalBytesToRead = self.totalBytesToRead - buffer.length;
  1523. self.push(buffer);
  1524. } else if(buffer.length > self.totalBytesToRead) {
  1525. self.totalBytesToRead = self.totalBytesToRead - buffer._index;
  1526. self.push(buffer.slice(0, buffer._index));
  1527. }
  1528. // Finished reading
  1529. if(self.totalBytesToRead <= 0) {
  1530. self.endCalled = true;
  1531. }
  1532. });
  1533. }
  1534. // Set read length
  1535. var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize;
  1536. if(!self.gs.isOpen) {
  1537. self.gs.open(function(err, gs) {
  1538. self.totalBytesToRead = self.gs.length - self.gs.position;
  1539. if(err) return self.emit('error', err);
  1540. read();
  1541. });
  1542. } else {
  1543. read();
  1544. }
  1545. }
  1546. GridStoreStream.prototype.destroy = function() {
  1547. this.pause();
  1548. this.endCalled = true;
  1549. this.gs.close();
  1550. this.emit('end');
  1551. }
  1552. GridStoreStream.prototype.write = function(chunk, encoding, callback) {
  1553. var self = this;
  1554. if(self.endCalled) return self.emit('error', MongoError.create({message: 'attempting to write to stream after end called', driver:true}))
  1555. // Do we have to open the gridstore
  1556. if(!self.gs.isOpen) {
  1557. self.gs.open(function() {
  1558. self.gs.isOpen = true;
  1559. self.gs.write(chunk, function() {
  1560. process.nextTick(function() {
  1561. self.emit('drain');
  1562. });
  1563. });
  1564. });
  1565. return false;
  1566. } else {
  1567. self.gs.write(chunk, function() {
  1568. self.emit('drain');
  1569. });
  1570. return true;
  1571. }
  1572. }
  1573. GridStoreStream.prototype.end = function(chunk, encoding, callback) {
  1574. var self = this;
  1575. var args = Array.prototype.slice.call(arguments, 0);
  1576. callback = args.pop();
  1577. if(typeof callback != 'function') args.push(callback);
  1578. chunk = args.length ? args.shift() : null;
  1579. encoding = args.length ? args.shift() : null;
  1580. self.endCalled = true;
  1581. if(chunk) {
  1582. self.gs.write(chunk, function() {
  1583. self.gs.close(function() {
  1584. if(typeof callback == 'function') callback();
  1585. self.emit('end')
  1586. });
  1587. });
  1588. }
  1589. self.gs.close(function() {
  1590. if(typeof callback == 'function') callback();
  1591. self.emit('end')
  1592. });
  1593. }
  1594. /**
  1595. * 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.
  1596. * @function external:Duplex#read
  1597. * @param {number} size Optional argument to specify how much data to read.
  1598. * @return {(String | Buffer | null)}
  1599. */
  1600. /**
  1601. * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
  1602. * @function external:Duplex#setEncoding
  1603. * @param {string} encoding The encoding to use.
  1604. * @return {null}
  1605. */
  1606. /**
  1607. * This method will cause the readable stream to resume emitting data events.
  1608. * @function external:Duplex#resume
  1609. * @return {null}
  1610. */
  1611. /**
  1612. * 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.
  1613. * @function external:Duplex#pause
  1614. * @return {null}
  1615. */
  1616. /**
  1617. * 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.
  1618. * @function external:Duplex#pipe
  1619. * @param {Writable} destination The destination for writing data
  1620. * @param {object} [options] Pipe options
  1621. * @return {null}
  1622. */
  1623. /**
  1624. * This method will remove the hooks set up for a previous pipe() call.
  1625. * @function external:Duplex#unpipe
  1626. * @param {Writable} [destination] The destination for writing data
  1627. * @return {null}
  1628. */
  1629. /**
  1630. * 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.
  1631. * @function external:Duplex#unshift
  1632. * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue.
  1633. * @return {null}
  1634. */
  1635. /**
  1636. * 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.)
  1637. * @function external:Duplex#wrap
  1638. * @param {Stream} stream An "old style" readable stream.
  1639. * @return {null}
  1640. */
  1641. /**
  1642. * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.
  1643. * @function external:Duplex#write
  1644. * @param {(string|Buffer)} chunk The data to write
  1645. * @param {string} encoding The encoding, if chunk is a String
  1646. * @param {function} callback Callback for when this chunk of data is flushed
  1647. * @return {boolean}
  1648. */
  1649. /**
  1650. * 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.
  1651. * @function external:Duplex#end
  1652. * @param {(string|Buffer)} chunk The data to write
  1653. * @param {string} encoding The encoding, if chunk is a String
  1654. * @param {function} callback Callback for when this chunk of data is flushed
  1655. * @return {null}
  1656. */
  1657. /**
  1658. * GridStoreStream stream data event, fired for each document in the cursor.
  1659. *
  1660. * @event GridStoreStream#data
  1661. * @type {object}
  1662. */
  1663. /**
  1664. * GridStoreStream stream end event
  1665. *
  1666. * @event GridStoreStream#end
  1667. * @type {null}
  1668. */
  1669. /**
  1670. * GridStoreStream stream close event
  1671. *
  1672. * @event GridStoreStream#close
  1673. * @type {null}
  1674. */
  1675. /**
  1676. * GridStoreStream stream readable event
  1677. *
  1678. * @event GridStoreStream#readable
  1679. * @type {null}
  1680. */
  1681. /**
  1682. * GridStoreStream stream drain event
  1683. *
  1684. * @event GridStoreStream#drain
  1685. * @type {null}
  1686. */
  1687. /**
  1688. * GridStoreStream stream finish event
  1689. *
  1690. * @event GridStoreStream#finish
  1691. * @type {null}
  1692. */
  1693. /**
  1694. * GridStoreStream stream pipe event
  1695. *
  1696. * @event GridStoreStream#pipe
  1697. * @type {null}
  1698. */
  1699. /**
  1700. * GridStoreStream stream unpipe event
  1701. *
  1702. * @event GridStoreStream#unpipe
  1703. * @type {null}
  1704. */
  1705. /**
  1706. * GridStoreStream stream error event
  1707. *
  1708. * @event GridStoreStream#error
  1709. * @type {null}
  1710. */
  1711. /**
  1712. * @ignore
  1713. */
  1714. module.exports = GridStore;