This was a quick personal project where all my photos from my phone were imported into a single folder. Normally, I want all my photos distributed into folders where the folder name is the date the photos were taken.
If it was just a few photos, I’d create the folder manually and then drag the photos into separate folders, but this was about 1600 photos and videos.
I needed a program that would look at the date of the file/photo/video, create a folder based on the date, and then move the file/image/video into that folder. I thought, why not do this with javascript.
I already have node.js on installed on my machine which gives me the ability to run javascript and manage my files.
Here’s the quick batch program I created:
var fs = require("fs");
var currentDir = '/photos';
var dest = "/temp";
var errors = Array();
//Get the list of photos and videos
var listing = fs.readdirSync(currentDir);
//NOTE: node.js automatically supports the new arrow functions. No transpilers needed
listing.forEach( (name) => {
file= fs.statSync(currentDir + "/" + name);
var date = new Date(file.mtime);
var year = date.getFullYear();
var day = date.getDate();
day = day > 9 ? day : "0" + day;
var month = date.getMonth() + 1;
month = month > 9 ? month : "0" + month;
var foldername = year + "-" + month + "-" + day;
// if the directory already exists, it will error, but since the error is caught, the program continues
try {
fs.mkdirSync( dest + "/" + foldername );
} catch(err){ errors.push(name + ": " + err[0]); };
// move the file - see NOTE below
try {
fs.rename(currentDir + "/" + name, dest + "/" + foldername + "/" + name);
} catch(err){errors.push(name + ": " + err[0]); };
});
errors.forEach((err) => console.log(err));
The folder names need to be in a YYYY-MM-DD format. The getDate and getMonth methods returns an integer. To get the double digit day or month the day = day > 9 ? day : '0' + day;
line adds a zero if the day is a single digit.
NOTE: the fs.rename is used to copy the files and it may have difficulty doing that if you are trying to move to a different partition or different hard drive. I ran this all on an external drive and once it completed, dragged the folders and images in bulk to the final destination which was on a different drive.