Skip to content

Commit

Permalink
refactoring, ESLint set up
Browse files Browse the repository at this point in the history
  • Loading branch information
Aslan Baryshnikov committed Apr 25, 2022
1 parent bf08fbd commit a7aeaea
Show file tree
Hide file tree
Showing 8 changed files with 9,166 additions and 111 deletions.
16 changes: 16 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"env": {
"commonjs": true,
"es2021": true,
"node": true
},
"extends": [
"airbnb-base"
],
"parserOptions": {
"ecmaVersion": "latest"
},
"rules": {
"no-console": "off"
}
}
12 changes: 5 additions & 7 deletions helpers/convertBytes.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
const convertBytes = (bytes) => {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];

if (bytes === 0)
return 'n/a';
if (bytes === 0) return 'n/a';

const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
const i = parseInt(String(Math.floor(Math.log(bytes) / Math.log(1024))), 10);

if (i === 0)
return bytes + ' ' + sizes[i];
if (i === 0) return `${bytes} ${sizes[i]}`;

return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
return `${(bytes / 1024 ** i).toFixed(1)} ${sizes[i]}`;
};

module.exports = convertBytes;
20 changes: 20 additions & 0 deletions helpers/getAllDirectories.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const fs = require('fs');
const path = require('path');

const getAllDirectories = (sourcePath) => {
const directories = [sourcePath];

function throughDirectory(directory) {
fs.readdirSync(directory).forEach((item) => {
const absolute = path.join(directory, item);
if (!fs.statSync(absolute).isDirectory()) return;
directories.push(absolute);
throughDirectory(absolute);
});
}
throughDirectory(sourcePath);

return directories;
};

module.exports = getAllDirectories;
21 changes: 11 additions & 10 deletions helpers/getAllFiles.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@ const fs = require('fs');
const path = require('path');

const getAllFiles = (dirPath, arrayOfFiles = []) => {
const files = fs.readdirSync(dirPath);
const files = fs.readdirSync(dirPath);

files.forEach(function(file) {
if (fs.statSync(dirPath + '/' + file).isDirectory()) {
arrayOfFiles = getAllFiles(dirPath + '/' + file, arrayOfFiles);
} else {
arrayOfFiles.push(path.join(dirPath, file));
}
})
files.forEach((file) => {
if (fs.statSync(`${dirPath}/${file}`).isDirectory()) {
// eslint-disable-next-line no-param-reassign
arrayOfFiles = getAllFiles(`${dirPath}/${file}`, arrayOfFiles);
} else {
arrayOfFiles.push(path.join(dirPath, file));
}
});

return arrayOfFiles;
}
return arrayOfFiles;
};

module.exports = getAllFiles;
14 changes: 7 additions & 7 deletions helpers/getTotalSize.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ const fs = require('fs');
const getAllFiles = require('./getAllFiles');

const getTotalSize = (directoryPath) => {
const arrayOfFiles = getAllFiles(directoryPath);
const arrayOfFiles = getAllFiles(directoryPath);

let totalSize = 0;
let totalSize = 0;

arrayOfFiles.forEach(function(filePath) {
totalSize += fs.statSync(filePath).size;
})
arrayOfFiles.forEach((filePath) => {
totalSize += fs.statSync(filePath).size;
});

return totalSize;
}
return totalSize;
};

module.exports = getTotalSize;
164 changes: 78 additions & 86 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const fs = require('fs');
const path = require('path');
const imagemin = require('imagemin');
const imageminGifsicle = require('imagemin-gifsicle');
const imageminMozjpeg = require('imagemin-mozjpeg');
Expand All @@ -8,104 +6,98 @@ const imageminSvgo = require('imagemin-svgo');
const imageminWebp = require('imagemin-webp');
const convertBytes = require('./helpers/convertBytes');
const getTotalSize = require('./helpers/getTotalSize');
const getAllDirectories = require('./helpers/getAllDirectories');

const PACKAGE_NAME = 'image-optimist';
const PROCESSING_TIME = 'Processing time';

const imageOptimist = async (config) => {
console.time(PROCESSING_TIME);
console.log(`${PACKAGE_NAME} started`);
console.time(PROCESSING_TIME);
console.log(`${PACKAGE_NAME} started`);

const c = Object.assign({
sourcePath: null,
destinationPath: null,
mask: '*.{jpg,jpeg,png,svg,gif}',
webp: [
imageminWebp({
quality: 90,
method: 4,
metadata: 'none',
}),
],
plugins: [
imageminMozjpeg({
quality: 90,
}),
imageminPngquant({
speed: 4,
strip: true,
quality: [0.8, 1],
dithering: false,
verbose: true,
}),
imageminSvgo(),
imageminGifsicle({
optimizationLevel: 3,
}),
],
}, config);
const c = {
sourcePath: null,
destinationPath: null,
mask: '*.{jpg,jpeg,png,svg,gif}',
webp: [
imageminWebp({
quality: 90,
method: 4,
metadata: 'none',
}),
],
plugins: [
imageminMozjpeg({
quality: 90,
}),
imageminPngquant({
speed: 4,
strip: true,
quality: [0.8, 1],
dithering: false,
verbose: true,
}),
imageminSvgo(),
imageminGifsicle({
optimizationLevel: 3,
}),
],
...config,
};

const errors = [];
if (c.sourcePath === null)
errors.push('sourcePath is required');
if (c.destinationPath === null)
errors.push('destinationPath is required');
if (errors.length !== 0)
console.error(JSON.stringify(errors));
const errors = [];
if (c.sourcePath === null) errors.push('sourcePath is required');
if (c.destinationPath === null) errors.push('destinationPath is required');
if (errors.length !== 0) console.error(JSON.stringify(errors));

const initialDirSize = getTotalSize(c.sourcePath);
const initialDirSize = getTotalSize(c.sourcePath);

try {
// Collect directory paths
const inputDirectories = [c.sourcePath];
function throughDirectory(directory) {
fs.readdirSync(directory).forEach(item => {
const absolute = path.join(directory, item);
if (!fs.statSync(absolute).isDirectory()) return;
inputDirectories.push(absolute);
throughDirectory(absolute);
});
}
throughDirectory(c.sourcePath);
try {
const inputDirectories = getAllDirectories(c.sourcePath);

// Basic processing
const outputDirectories = [c.destinationPath];
for (const directory of inputDirectories) {
const input = `${directory}/${c.mask}`;
const output = directory.replace(c.sourcePath, c.destinationPath);
const relativePath = '.' + directory.replace(c.sourcePath, '');
outputDirectories.push(output);
console.log(`Images from ${relativePath} are being processed...`);
await imagemin([input], {
destination: output,
plugins: c.plugins,
});
}
// Basic processing
const outputDirectories = [c.destinationPath];
// eslint-disable-next-line no-restricted-syntax
for (const directory of inputDirectories) {
const input = `${directory}/${c.mask}`;
const output = directory.replace(c.sourcePath, c.destinationPath);
const relativePath = `.${directory.replace(c.sourcePath, '')}`;
outputDirectories.push(output);
console.log(`Images from ${relativePath} are being processed...`);
// eslint-disable-next-line no-await-in-loop
await imagemin([input], {
destination: output,
plugins: c.plugins,
});
}

// Conversion to webp
if (c.webp) {
for (const directory of outputDirectories) {
const input = `${directory}/*.{jpeg,jpg,png}`;
const relativePath = '.' + directory.replace(c.destinationPath, '');
console.log(`Images from ${relativePath} are being converted to webp...`);
await imagemin([input], {
destination: directory,
plugins: c.webp,
});
}
}
} catch (e) {
return console.error(`${PACKAGE_NAME} finished with error:\n`, e);
// Conversion to webp
if (c.webp) {
// eslint-disable-next-line no-restricted-syntax
for (const directory of outputDirectories) {
const input = `${directory}/*.{jpeg,jpg,png}`;
const relativePath = `.${directory.replace(c.destinationPath, '')}`;
console.log(`Images from ${relativePath} are being converted to webp...`);
// eslint-disable-next-line no-await-in-loop
await imagemin([input], {
destination: directory,
plugins: c.webp,
});
}
}
} catch (e) {
console.error(`${PACKAGE_NAME} finished with error:\n`, e);
return;
}

const finalDirSize = getTotalSize(c.destinationPath);
const diffDirSize = initialDirSize - finalDirSize;
const finalDirSize = getTotalSize(c.destinationPath);
const diffDirSize = initialDirSize - finalDirSize;

console.log(`Initial: ${convertBytes(initialDirSize)}`);
console.log(`Final${c.webp ? ' + webp' : ''}: ${convertBytes(finalDirSize)}`);
console.log(`Diff: ${convertBytes(diffDirSize)}`);
console.timeEnd(PROCESSING_TIME);
console.log(`${PACKAGE_NAME} finished`);
console.log(`Initial: ${convertBytes(initialDirSize)}`);
console.log(`Final${c.webp ? ' + webp' : ''}: ${convertBytes(finalDirSize)}`);
console.log(`Diff: ${convertBytes(diffDirSize)}`);
console.timeEnd(PROCESSING_TIME);
console.log(`${PACKAGE_NAME} finished`);
};

module.exports = imageOptimist;
Loading

0 comments on commit a7aeaea

Please sign in to comment.