Skip to content

Instantly share code, notes, and snippets.

@ethan605
Created July 20, 2020 14:10
Show Gist options
  • Save ethan605/9e65349e6f3a87c8d549c3f9dd7f7acb to your computer and use it in GitHub Desktop.
Save ethan605/9e65349e6f3a87c8d549c3f9dd7f7acb to your computer and use it in GitHub Desktop.
const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const fp = require('lodash/fp');
const anyAscii = require('any-ascii');
const BASE_PATH = '~/Downloads/';
function normalizeTitle(title) {
return fp.flow(
fp.split(' - '),
fp.reverse,
fp.map(part => _.startCase(_.toLower(part))),
fp.join(' - ')
)(anyAscii(title));
}
function normalizeInDir(...args) {
const dirPath = path.resolve(BASE_PATH, ...args);
try {
const files = fs.readdirSync(dirPath).filter(fileName => !_.startsWith(fileName, '.'));
files.forEach(fileName => {
const extName = path.extname(fileName);
const newName = normalizeTitle(path.basename(fileName, extName)) + extName;
fs.renameSync(path.resolve(dirPath, fileName), path.resolve(dirPath, newName));
});
} catch (err) {
console.log('Err:', err);
}
}
function groupByAuthor(...args) {
const dirPath = path.resolve(BASE_PATH, ...args);
try {
const files = fs.readdirSync(dirPath).filter(fileName => !_.startsWith(fileName, '.'));
const groupedFiles = _.groupBy(files, fileName => {
const author = fileName.split(' - ')[0];
return author;
});
_.toPairs(groupedFiles)
.filter(([_author, titles]) => titles.length >= 3)
.forEach(([author, titles]) => {
fs.mkdirSync(path.resolve(dirPath, author));
titles.forEach(title => fs.renameSync(path.resolve(dirPath, title), path.resolve(dirPath, author, title)));
});
} catch (err) {
console.log('Err:', err);
}
}
module.exports = { normalizeInDir, groupByAuthor };
{
"name": "converter",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"any-ascii": "^0.1.5",
"lodash": "^4.17.19"
},
"devDependencies": {
"eslint": "^7.4.0",
"prettier": "^2.0.5"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment