grid_store.js 65 KB

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