fileFactory.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. const {
  3. isFunc,
  4. debugLog,
  5. moveFile,
  6. promiseCallback,
  7. checkAndMakeDir,
  8. saveBufferToFile
  9. } = require('./utilities');
  10. /**
  11. * Returns Local function that moves the file to a different location on the filesystem
  12. * which takes two function arguments to make it compatible w/ Promise or Callback APIs
  13. * @param {String} filePath - destination file path.
  14. * @param {Object} options - file factory options.
  15. * @param {Object} fileUploadOptions - middleware options.
  16. * @returns {Function}
  17. */
  18. const moveFromTemp = (filePath, options, fileUploadOptions) => (resolve, reject) => {
  19. debugLog(fileUploadOptions, `Moving temporary file ${options.tempFilePath} to ${filePath}`);
  20. moveFile(options.tempFilePath, filePath, promiseCallback(resolve, reject));
  21. };
  22. /**
  23. * Returns Local function that moves the file from buffer to a different location on the filesystem
  24. * which takes two function arguments to make it compatible w/ Promise or Callback APIs
  25. * @param {String} filePath - destination file path.
  26. * @param {Object} options - file factory options.
  27. * @param {Object} fileUploadOptions - middleware options.
  28. * @returns {Function}
  29. */
  30. const moveFromBuffer = (filePath, options, fileUploadOptions) => (resolve, reject) => {
  31. debugLog(fileUploadOptions, `Moving uploaded buffer to ${filePath}`);
  32. saveBufferToFile(options.buffer, filePath, promiseCallback(resolve, reject));
  33. };
  34. module.exports = (options, fileUploadOptions = {}) => {
  35. // see: https://github.com/richardgirges/express-fileupload/issues/14
  36. // firefox uploads empty file in case of cache miss when f5ing page.
  37. // resulting in unexpected behavior. if there is no file data, the file is invalid.
  38. // if (!fileUploadOptions.useTempFiles && !options.buffer.length) return;
  39. // Create and return file object.
  40. return {
  41. name: options.name,
  42. data: options.buffer,
  43. size: options.size,
  44. encoding: options.encoding,
  45. tempFilePath: options.tempFilePath,
  46. truncated: options.truncated,
  47. mimetype: options.mimetype,
  48. md5: options.hash,
  49. mv: (filePath, callback) => {
  50. // Define a propper move function.
  51. const moveFunc = fileUploadOptions.useTempFiles
  52. ? moveFromTemp(filePath, options, fileUploadOptions)
  53. : moveFromBuffer(filePath, options, fileUploadOptions);
  54. // Create a folder for a file.
  55. checkAndMakeDir(fileUploadOptions, filePath);
  56. // If callback is passed in, use the callback API, otherwise return a promise.
  57. return isFunc(callback) ? moveFunc(callback) : new Promise(moveFunc);
  58. }
  59. };
  60. };