Skip to content

Commit

Permalink
Update utilities.js
Browse files Browse the repository at this point in the history
Make it lighter
  • Loading branch information
RomanBurunkov authored Jun 6, 2019
1 parent e9a5f2f commit a61e8bf
Showing 1 changed file with 40 additions and 69 deletions.
109 changes: 40 additions & 69 deletions lib/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()}`;
};

Expand All @@ -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]);
Expand All @@ -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];
Expand All @@ -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);
};

Expand All @@ -169,39 +154,31 @@ 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));
};

/**
* Save buffer data to a file.
* @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);
};

Expand All @@ -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 (
Expand All @@ -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 = {
Expand Down

0 comments on commit a61e8bf

Please sign in to comment.