Skip to content

Instantly share code, notes, and snippets.

@2xAA
Created October 28, 2022 14:31
Show Gist options
  • Save 2xAA/1320b9b00f9406ffee8f17ade56a446c to your computer and use it in GitHub Desktop.
Save 2xAA/1320b9b00f9406ffee8f17ade56a446c to your computer and use it in GitHub Desktop.
Take a directory of files and move them into directories based on the first letter of the file
// Usage:
// 1. npm init -y && npm i minimist
// 2. node sort-files-into-alphabetical-directories.js /directory-of-files /directory-of-files/output
const fs = require("fs");
const path = require("path");
const argv = require("minimist")(process.argv.slice(2));
const alphabet = [..."abcdefghijklmnopqrstuvwxyz"];
const readPath = argv._[0];
const outputPath = argv._[1];
fs.readdir(readPath, (err, files) => {
alphabet.forEach((letter) => {
const letterOutputPath = path.join(outputPath, letter.toLocaleUpperCase());
if (!fs.existsSync(letterOutputPath)) {
fs.mkdirSync(letterOutputPath);
}
const toMatch = new RegExp(`^(${letter})(?:.*)$`, "g");
files
.filter((fileName) => fileName.toLocaleLowerCase().match(toMatch))
.forEach((fileName) => {
const oldPath = path.join(readPath, fileName);
const newPath = path.join(
outputPath,
letter.toLocaleUpperCase(),
fileName
);
fs.rename(oldPath, newPath, (err) => {
if (err) {
throw err;
}
console.log("Moved", `"${fileName}"`, "to", newPath);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment