UNPKG

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