Skip to content

Instantly share code, notes, and snippets.

@Mottie
Created January 18, 2018 20:32
Show Gist options
  • Save Mottie/b0bf552ffcead45204a561a547dbe2a6 to your computer and use it in GitHub Desktop.
Save Mottie/b0bf552ffcead45204a561a547dbe2a6 to your computer and use it in GitHub Desktop.
Convert M/D/YYYY format to YYYY-MM-DD in all markdown files in current folder
#!/usr/bin/env node
"use strict";
/* Convert date formats in markdown
*
* This script converts a "(M/D/YYYY)" date format to "(YYYY-MM-DD)" in *all*
* markdown files within the folder it is placed
* Use `node convert-date-in-md.js` to execute
*/
const fs = require("fs");
const regex = /(\(\d+\/\d+\/\d+\))/g;
function padZero(number) {
return ("0" + number).slice(-2);
}
// Convert (M/D/YYYY) to (YYYY-MM-DD)
function convertDates(string) {
return string.replace(regex, date => {
const [, m, d, y] = date.split(/[(/)]/);
return `(${y}-${padZero(m)}-${padZero(d)})`;
})
}
function processMarkdownInFolder() {
return new Promise((resolve, reject) => {
const path = "./";
fs.readdir(path, (err, files) => {
if (err) {
console.log("Error reading the current folder", err);
reject(err);
}
return Promise.all(files.map(file => {
if (file.endsWith(".md")) {
readFile(path + file).then(content => writeFile(file, convertDates(content)));
}
Promise.resolve();
}))
.then(resolve)
.catch(exit);
});
});
}
function readFile(name) {
return new Promise((resolve, reject) => {
fs.readFile(name, "utf8", (err, file) => {
if (err) {
return reject(err);
}
resolve(file);
});
});
}
function writeFile(name, obj) {
return new Promise((resolve, reject) => {
fs.writeFile(name, obj, "utf8", err => {
if (err) {
console.log(`Error writing ${name}`, err);
return reject(err);
}
resolve();
});
});
}
function exit(err) {
if (err) console.error(err);
process.exit(err ? 1 : 0);
}
processMarkdownInFolder().then(() => console.log("\x1b[32m%s\x1b[0m", "Date conversion complete"));
@Mottie
Copy link
Author

Mottie commented Jan 18, 2018

The script was used for this wiki page conversion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment