memHandler.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const crypto = require('crypto');
  2. const { debugLog } = require('./utilities');
  3. /**
  4. * memHandler - In memory upload handler
  5. * @param {Object} options
  6. * @param {String} fieldname
  7. * @param {String} filename
  8. * @returns {Object}
  9. */
  10. module.exports = (options, fieldname, filename) => {
  11. const buffers = [];
  12. const hash = crypto.createHash('md5');
  13. let fileSize = 0;
  14. let completed = false;
  15. const getBuffer = () => Buffer.concat(buffers, fileSize);
  16. return {
  17. dataHandler: (data) => {
  18. if (completed === true) {
  19. debugLog(options, `Error: got ${fieldname}->${filename} data chunk for completed upload!`);
  20. return;
  21. }
  22. buffers.push(data);
  23. hash.update(data);
  24. fileSize += data.length;
  25. debugLog(options, `Uploading ${fieldname}->${filename}, bytes:${fileSize}...`);
  26. },
  27. getBuffer: getBuffer,
  28. getFilePath: () => '',
  29. getFileSize: () => fileSize,
  30. getHash: () => hash.digest('hex'),
  31. complete: () => {
  32. debugLog(options, `Upload ${fieldname}->${filename} completed, bytes:${fileSize}.`);
  33. completed = true;
  34. return getBuffer();
  35. },
  36. cleanup: () => { completed = true; },
  37. getWritePromise: () => Promise.resolve()
  38. };
  39. };