Skip to content

Instantly share code, notes, and snippets.

@hsribei
Created July 11, 2018 03:20
Show Gist options
  • Save hsribei/13dfd3ae45df0f9881b1567ee37bcd8a to your computer and use it in GitHub Desktop.
Save hsribei/13dfd3ae45df0f9881b1567ee37bcd8a to your computer and use it in GitHub Desktop.
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