Skip to content

Instantly share code, notes, and snippets.

@iwestlin
Created May 11, 2020 17:35
Show Gist options
  • Save iwestlin/834f3b491c4fb2e02971da67d4098cb3 to your computer and use it in GitHub Desktop.
Save iwestlin/834f3b491c4fb2e02971da67d4098cb3 to your computer and use it in GitHub Desktop.
batch rename files in some directory
const fs = require('fs')
const DIR = 'this is the directory you want to process'
const STRING_TO_REMOVE_IN_FILENAME = 'this is the string in file name which you want to replace'
const NEW_STRING = 'this is the string you want to replace with'
rename_file_in_dir({dir: DIR, str: STRING_TO_REMOVE_IN_FILENAME, newstr: NEW_STRING})
function rename_file_in_dir ({dir, str, newstr}) {
// const files = fs.readdirSync(dir, {withFileTypes: true}).map(file => ({name: file.name, is_dir: file.isDirectory()}))
// for lower version of node which not support 'withFileTypes'
const files = fs.readdirSync(dir).map(name => ({name, is_dir: fs.statSync(`${dir}/${name}`).isDirectory()}))
files.forEach(file => {
const {name, is_dir} = file
if (is_dir) return rename_file_in_dir({dir: `${dir}/${name}`, str, newstr})
let new_name = name.replace(str, newstr)
if (new_name === name) return
if (!name.startsWith('.') && new_name.startsWith('.')) new_name = Date.now() + new_name
const old_path = `${dir}/${name}`
const new_path = `${dir}/${new_name}`
// return console.log('rename', old_path, 'to', new_path) // you might want to see the files that will be renamed first
fs.rename(old_path, new_path, err => {
err ? console.error(err) : console.log('rename', old_path, 'to', new_path)
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment