script for mass moving files to <date-published>-<filename>
/** | |
* utility I used to rename all of my files based on the date | |
* so that I can use netlify+dropbox to "schedule" posts | |
* Example... | |
* original filepath: Apps/chaseadams.io/articles/2019/yolo.md | |
* frontmatter contains "date: "2019-01-01" | |
* new filepath: Apps/chaseadams.io/articles/2019/2019-01-01-yolo.md | |
*/ | |
const fs = require("fs"); | |
const path = require("path"); | |
const root = "./Apps/chaseadams.io/articles"; | |
walkTree(root); | |
function walkTree(prevPath) { | |
fs.readdir(prevPath, (err, files) => { | |
if (err) { | |
console.error(err); | |
process.exit(1); | |
} | |
files.forEach(filepath => { | |
const newPath = path.join(prevPath, filepath); | |
fs.stat(newPath, (err, stats) => { | |
if (err) { | |
console.error(err); | |
process.exit(1); | |
} | |
if (stats.isDirectory()) { | |
walkTree(newPath); | |
} else { | |
if (!newPath.match(/\d{4}-\d{2}-\d{2}/)) { | |
fs.readFile(newPath, "utf8", (err, contents) => { | |
const frontmatter = contents | |
.split("---", 2) | |
.splice(1)[0] | |
.split("\n") | |
.forEach(date => { | |
if (date.startsWith("date: ")) { | |
date = date.split(": ")[1].replace(/"/g, ""); | |
if (date.match(/T/)) { | |
date = date.split("T")[0]; | |
} | |
let newNewPath = newPath.split("/"); | |
newNewPath[newNewPath.length - 1] = `${date}-${ | |
newNewPath[newNewPath.length - 1] | |
}`; | |
newNewPath = newNewPath.join("/"); | |
fs.rename(newPath, newNewPath, err => { | |
if (err) { | |
console.error(err); | |
process.exit(1); | |
} | |
console.log( | |
`${newPath} successfully renamed to ${newNewPath}` | |
); | |
}); | |
} | |
}); | |
}); | |
} | |
} | |
}); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment