Created
August 13, 2020 17:44
-
-
Save luciopaiva/457b0607c78c7082d37d841cb5a6b1bd to your computer and use it in GitHub Desktop.
Quick script to change timestamps of files in given directory
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
/* | |
* This script changes the timestamps of a series of files in batch. The script will go through all files in | |
* specified folder, ordering them by name. The first file will be stamped with given start date. The second one will | |
* be stamped with start date plus 1 second, the third with start date plus 2 seconds, and so on. | |
* | |
* But why? I had a series of photos that I wanted to upload to the cloud and their timestamps did not represent the | |
* actual date when they were taken. The photos were all taken in the same day and I knew what day was that, so I just | |
* needed a script to do it in batch for me. Also, files were sequentially named by the digital camera, and although I | |
* didn't know the exact time of day each photo was taken, I could at least preserve the sequence, that's why I decided | |
* to stamp each one second after the other, ordered by name. | |
* | |
* # How to use | |
* | |
* Considering you have Node.js already installed, install moment: | |
* | |
* npm install moment | |
* | |
* Constants to set before running: | |
* | |
* DIRECTORY | |
* START_DATE | |
* | |
* Attention: all files in DIRECTORY will have their timestamps changed! | |
* | |
*/ | |
const DIRECTORY = "/path/to/folder"; | |
const START_DATE = "2001-01-01T00:00:00.000Z"; | |
const fs = require("fs"); | |
const path = require("path"); | |
const moment = require("moment"); | |
const date = moment(START_DATE); | |
// sort files by name (ascending) | |
const sortedFiles = Array.from(fs.readdirSync(DIRECTORY)).sort((a, b) => { | |
const al = a.toLocaleLowerCase(); | |
const bl = b.toLocaleLowerCase(); | |
return al.localeCompare(bl); | |
}); | |
// iterate through files changing their dates | |
for (const fileName of sortedFiles) { | |
const fullName = path.join(DIRECTORY, fileName); | |
// change file timestamp (both access and modified dates) | |
const fd = fs.openSync(fullName, "r"); | |
const time = date.toDate(); | |
fs.futimesSync(fd, time, time); | |
fs.closeSync(fd); | |
console.info(`"${fileName}" done`); | |
date.add(1, "second"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment