From a61e8bf3d18674e50ae226449e42d9b9d192cc98 Mon Sep 17 00:00:00 2001 From: Roman Burunkov Date: Thu, 6 Jun 2019 11:14:58 +0300 Subject: [PATCH] Update utilities.js Make it lighter --- lib/utilities.js | 109 +++++++++++++++++------------------------------ 1 file changed, 40 insertions(+), 69 deletions(-) diff --git a/lib/utilities.js b/lib/utilities.js index 3a854bf..8e3c2fb 100644 --- a/lib/utilities.js +++ b/lib/utilities.js @@ -33,8 +33,7 @@ const debugLog = (options, msg) => { */ const getTempFilename = (prefix) => { prefix = prefix || TEMP_PREFIX; - tempCounter ++; - if (tempCounter > TEMP_COUNTER_MAX) tempCounter = 1; + tempCounter = tempCounter >= TEMP_COUNTER_MAX ? 1 : tempCounter + 1; return `${prefix}-${tempCounter}-${Date.now()}`; }; @@ -55,21 +54,15 @@ const errorFunc = (resolve, reject) => isFunc(reject) ? reject : resolve; * @returns {Function} */ const promiseCallback = (resolve, reject) => { - return (err) => { - if (err) { - errorFunc(resolve, reject)(err); - } else { - resolve(); - } - }; + return err => err ? errorFunc(resolve, reject)(err) : resolve(); }; /** - * Builds instance options from arguments objects. + * Builds instance options from arguments objects(can't be arrow function). * @returns {Object} - result options. */ const buildOptions = function(){ - let result = {}; + const result = {}; [...arguments].forEach(options => { if (!options || typeof options !== 'object') return; Object.keys(options).forEach(key => result[key] = options[key]); @@ -85,17 +78,15 @@ const buildOptions = function(){ * @returns {Object} */ const buildFields = (instance, field, value) => { - //Do nothing if value is not set. - if (value === null || value === undefined){ - return instance; - } + // Do nothing if value is not set. + if (value === null || value === undefined) return instance; instance = instance || {}; // Non-array fields if (!instance[field]) { instance[field] = value; } else { // Array fields - if (instance[field] instanceof Array){ + if (instance[field] instanceof Array) { instance[field].push(value); } else { instance[field] = [instance[field], value]; @@ -108,57 +99,51 @@ const buildFields = (instance, field, value) => { * Creates a folder for file specified in the path variable * @param {Object} fileUploadOptions * @param {String} filePath + * @returns {Boolean} */ -const checkAndMakeDir = function(fileUploadOptions, filePath){ - //Check upload options were set. +const checkAndMakeDir = (fileUploadOptions, filePath) => { + // Check upload options were set. if (!fileUploadOptions) return false; if (!fileUploadOptions.createParentPath) return false; - //Check whether folder for the file exists. + // Check whether folder for the file exists. if (!filePath) return false; const parentPath = path.dirname(filePath); - //Create folder if it is not exists. - if (!fs.existsSync(parentPath)) fs.mkdirSync(parentPath); - return true; + // Create folder if it is not exists. + if (!fs.existsSync(parentPath)) fs.mkdirSync(parentPath, { recursive: true }); + // Checks folder again and return a results. + return fs.existsSync(parentPath); }; /** * Delete file. * @param {String} file - Path to the file to delete. */ -const deleteFile = (file, callback) => { - fs.unlink(file, (err) => { - if (err) { - callback(err); - return; - } - callback(); - }); -}; +const deleteFile = (file, callback) => fs.unlink(file, err => err ? callback(err) : callback()); /** * Copy file via streams * @param {String} src - Path to the source file * @param {String} dst - Path to the destination file. */ -const copyFile = function(src, dst, callback){ - //cbCalled flag and runCb helps to run cb only once. +const copyFile = (src, dst, callback) => { + // cbCalled flag and runCb helps to run cb only once. let cbCalled = false; let runCb = (err) => { if (cbCalled) return; cbCalled = true; callback(err); }; - //Create read stream + // Create read stream let readable = fs.createReadStream(src); readable.on('error', runCb); - //Create write stream + // Create write stream let writable = fs.createWriteStream(dst); writable.on('error', (err)=>{ readable.destroy(); runCb(err); }); writable.on('close', () => runCb()); - //Copy file via piping streams. + // Copy file via piping streams. readable.pipe(writable); }; @@ -169,15 +154,8 @@ const copyFile = function(src, dst, callback){ * @param {Function} callback - A callback function. */ const moveFile = (src, dst, callback) => { - // Copy file to dst. - copyFile(src, dst, (err) => { - if (err) { - callback(err); - return; - } - // Delete src file. - deleteFile(src, callback); - }); + // Copy file to dst and delete src whether success. + copyFile(src, dst, err => err ? callback(err) : deleteFile(src, callback)); }; /** @@ -185,23 +163,22 @@ const moveFile = (src, dst, callback) => { * @param {Buffer} buffer - buffer to save to a file. * @param {String} filePath - path to a file. */ -const saveBufferToFile = function(buffer, filePath, callback){ - if (!Buffer.isBuffer(buffer)){ - callback(new Error('buffer variable should be a Buffer!')); - return; +const saveBufferToFile = (buffer, filePath, callback) => { + if (!Buffer.isBuffer(buffer)) { + return callback(new Error('buffer variable should be type of Buffer!')); } - //Setup readable stream from buffer. + // Setup readable stream from buffer. let streamData = buffer; let readStream = Readable(); - readStream._read = ()=>{ + readStream._read = () => { readStream.push(streamData); streamData = null; }; - //Setup file system writable stream. + // Setup file system writable stream. let fstream = fs.createWriteStream(filePath); fstream.on('error', error => callback(error)); fstream.on('close', () => callback()); - //Copy file via piping streams. + // Copy file via piping streams. readStream.pipe(fstream); }; @@ -212,20 +189,16 @@ const saveBufferToFile = function(buffer, filePath, callback){ * @returns {Object} - {name, extension}. */ const parseFileNameExtension = (preserveExtension, fileName) => { - let preserveExtensionLengh = parseInt(preserveExtension); - let result = {name: fileName, extension: ''}; - if (!preserveExtension && preserveExtensionLengh !== 0){ - return result; - } + const preserveExtensionLengh = parseInt(preserveExtension); + const result = {name: fileName, extension: ''}; + if (!preserveExtension && preserveExtensionLengh !== 0) return result; // Define maximum extension length - let maxExtLength = isNaN(preserveExtensionLengh) + const maxExtLength = isNaN(preserveExtensionLengh) ? MAX_EXTENSION_LENGTH : Math.abs(preserveExtensionLengh); - let nameParts = fileName.split('.'); - if (nameParts.length < 2) { - return result; - } + const nameParts = fileName.split('.'); + if (nameParts.length < 2) return result; let extension = nameParts.pop(); if ( @@ -250,18 +223,16 @@ const parseFileNameExtension = (preserveExtension, fileName) => { * @returns {String} */ const parseFileName = (opts, fileName) => { - if (!opts.safeFileNames) { - return fileName; - } + if (!opts.safeFileNames) return fileName; // Set regular expression for the file name. - let safeNameRegex = typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp + const nameRegex = typeof opts.safeFileNames === 'object' && opts.safeFileNames instanceof RegExp ? opts.safeFileNames : SAFE_FILE_NAME_REGEX; // Parse file name extension. let {name, extension} = parseFileNameExtension(opts.preserveExtension, fileName); - if (extension.length) extension = '.' + extension.replace(safeNameRegex, ''); + if (extension.length) extension = '.' + extension.replace(nameRegex, ''); - return name.replace(safeNameRegex, '').concat(extension); + return name.replace(nameRegex, '').concat(extension); }; module.exports = {