Last active
November 21, 2021 15:46
-
-
Save goodwin64/b142d90d33e36fbd93871e31c094ca3a to your computer and use it in GitHub Desktop.
File counter rename script (0 external dependencies)
This file contains hidden or 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
// only built-in Node.js dependencies | |
const fs = require('fs') | |
const path = require('path') | |
const util = require('util') | |
// working dir | |
const dir = 'C:\\Users\\werey\\Documents\\Scanned Documents' | |
// difference between file name counter and page number on image | |
const offset = 5 | |
// temporary suffix (used only while program runs) | |
const TEMP_SUFFIX = 'TEMP_SUFFIX' | |
const rename = util.promisify(fs.rename); | |
async function main() { | |
// 1st loop - prepare for renaming: rename + add temp suffix (not to override files with names collision) | |
let files = fs.readdirSync(dir) | |
for (const file of files) { | |
// skip nested directories + misc files | |
if (!file.startsWith('Image')) { | |
continue; | |
} | |
const oldPath = path.resolve(dir, file) | |
console.log('old path ', oldPath) | |
const newName = file.replace(/(\d+)/g, (match, counter) => Number(counter) + offset).concat(TEMP_SUFFIX) | |
const newPath = path.resolve(dir, newName) | |
console.log('temp path 1', newPath) | |
console.log('\n') | |
await rename(oldPath, newPath); | |
} | |
// 2nd loop - final renaming: remove temp suffix | |
files = fs.readdirSync(dir) | |
for (const file of files) { | |
if (!file.startsWith('Image')) { | |
continue; | |
} | |
const oldPath = path.resolve(dir, file) | |
console.log('temp path 2', oldPath) | |
const newName = file.replace(TEMP_SUFFIX, '') | |
const newPath = path.resolve(dir, newName) | |
console.log('new path ', newPath) | |
console.log('\n') | |
await rename(oldPath, newPath); | |
} | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result