fileFactory.js 2.2 KB

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