Skip to content

Instantly share code, notes, and snippets.

@oaltman
Last active May 3, 2020 15:27
Show Gist options
  • Save oaltman/ec21792c4ddab637c48cefd6295f5b9c to your computer and use it in GitHub Desktop.
Save oaltman/ec21792c4ddab637c48cefd6295f5b9c to your computer and use it in GitHub Desktop.
Rename files
const fs = require('fs')
const path = require('path')
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const homedir = require('os').homedir()
const defaultInputFolder = path.join(homedir, 'Desktop', 'ImageRename')
const defaultOutputFolder = path.join(homedir, 'Desktop', 'ImageRenameOutput')
rl.question(`Input folder: [${defaultInputFolder}] `, function (userFolder) {
const inputFolder = userFolder || defaultInputFolder
fs.readdir(inputFolder, (err, contents) => {
console.log(`Found ${contents.length} files `)
if (err) {
console.log(err)
process.exit(1)
}
const numParse = /.*(\d+).*/
const numbers = contents
.map((filePath) => {
const match = numParse.exec(path.basename(filePath))
return match
? { filePath: path.join(inputFolder, filePath), value: parseInt(match[1]) }
: { filePath: path.join(inputFolder, filePath), value: 0 }
})
.sort((a, b) => b.value - a.value)
if (numbers.length === 0) {
console.log('no input files')
}
rl.question("Mode: [R,G,B]: ", function (modeInputUser) {
const modeInput = modeInputUser || "R,G,B"
const mode = modeInput.split(',').map(x => x.trim())
rl.question(`Output folder: [${defaultOutputFolder}]: `, function (outputFolderInput) {
const outputFolder = outputFolderInput || defaultOutputFolder
if (!fs.existsSync(outputFolder)){
console.log(`Output doesn't exist. Creating ${outputFolder}`)
fs.mkdirSync(outputFolder);
}
rl.question("Output files: [Image-%N-%M.jpg]: ", function (output) {
const outputMask = output || "Image-%N-%M.jpg"
let modeIndex = 0
let currentN = 1
numbers.forEach(number => {
const outputFile = path.join(outputFolder, outputMask
.replace('%M', `${mode[modeIndex]}`)
.replace('%N', `${currentN}`))
fs.copyFileSync(number.filePath, outputFile)
console.log(outputFile)
modeIndex++
if (modeIndex === mode.length) {
modeIndex = 0
currentN++
}
})
console.log(`Done. All files created in ${outputFolder}`)
rl.close()
})
})
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment