Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
List files recursively in nodejs then do some ad-hoc filtering and renaming
const fs = require('fs')
const path = require('path')
const child_process = require('child_process')
function getFilesRecursiveSync(folder) {
const fileContents = fs.readdirSync(folder)
return fileContents.reduce(function(matches, fileName) {
const filePath = path.join(folder, fileName)
const stats = fs.lstatSync(filePath)
if (stats.isDirectory()) {
const subFolder = filePath
const recurseReturn = matches.concat(getFilesRecursiveSync(subFolder))
return recurseReturn
} else {
const concatReturn = matches.concat([path.join(folder, fileName)])
return concatReturn
}
}, [])
}
function leftPadFile(f) {
const { dir, name, ext } = path.parse(f)
const newName = ('00' + name).slice(-2)
return path.format({ dir, name: newName, ext })
}
const mdFiles = getFilesRecursiveSync('./articles').filter(f =>
f.match(/\.md$/)
)
console.log({ mdFiles })
const newMdFiles = mdFiles.map(leftPadFile)
console.log({ newMdFiles })
// mdFiles.forEach(f => fs.renameSync(f, leftPadFile(f)))
mdFiles.forEach(mdFile => {
const newMdFile = leftPadFile(mdFile)
const gitOutput = child_process.execSync(`git mv -k ${mdFile} ${newMdFile}`)
console.log(gitOutput)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment