Created
July 31, 2022 07:32
-
-
Save HakamRaza/605dacbad3e6218a67415638c99c7754 to your computer and use it in GitHub Desktop.
Folder Grouping
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
| Created since I have multiple image files in one folder example: | |
| "Holiday at Hawaii 2022 - image 1.jpg" | |
| "Holiday at Hawaii 2022 - image 2.jpg" | |
| "Holiday at Hawaii 2022 - image 3.jpg" | |
| "Alex Birthday 2019 - IMG2021290219.jpg" | |
| "Alex Birthday 2019 - IMG2021901920.jpg" | |
| | |
| I want to move them to their own individual folder "Holiday at Hawaii 2022" & "Alex Birthday 2019" | |
| -------------------------------------------------- | |
| Require NodeJS > v10 installed. | |
| | |
| Steps to use: | |
| 1. Add this to your images folder | |
| 1. Run "node migrator.js" | |
*/ | |
const fs = require("fs"); | |
const path = require("path"); | |
const fileType = '.jpg'; // file types to move, excluding this remover.js file | |
const deliminator = " – "; // split title from filenames | |
let fileNames = []; // store current file names in folder | |
let collection = []; // multidemension arr store folder name, files list | |
/** | |
* Fetch all "jpg" files from current folder | |
*/ | |
fs.readdirSync(__dirname).forEach(file => { | |
if (file.endsWith(fileType)) { | |
fileNames = [...fileNames, file]; | |
}; | |
}); | |
/** | |
* Map respective files and title into object | |
*/ | |
while (fileNames.length > 0) { | |
// get title from filename | |
let title = fileNames[0].split(deliminator)[0]; | |
// find matching files in array | |
let files = fileNames.filter((item) => { | |
return item.startsWith(title + ' '); | |
}) | |
// update filename list by removing sorted files | |
// this considering filenames is already sorted by name from readdirSync | |
fileNames.splice(0, files.length); | |
//push to tempoary object collection | |
collection = [...collection, { | |
"title": title, | |
"files": files | |
}]; | |
} | |
/** | |
* Migrate files to respective directories | |
*/ | |
collection.forEach(object => { | |
object.files.forEach(file => { | |
const currentPath = path.join(__dirname, file); | |
const folderPath = path.join(__dirname, object.title); | |
const destinationPath = path.join(folderPath, file); | |
try { | |
// create directory | |
if (!fs.existsSync(folderPath)) { //check if folder already exists | |
fs.mkdirSync(folderPath); //creating folder | |
} | |
// move files | |
fs.rename(currentPath, destinationPath, function (err) { | |
if (err) { | |
throw err | |
} else { | |
console.log(`Moved ${file} to ${object.title}`); | |
} | |
}); | |
} catch (error) { | |
throw error; | |
} | |
}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment