const path = require('path')
const fs = require('fs').promises
const inputDir = 'c:\\temp\\journal'
const outputDir = 'c:\\temp\\journal-out'
async function * getFiles (dir) {
const dirents = await fs.readdir(dir, { withFileTypes: true })
for (const dirent of dirents) {
const res = path.resolve(dir, dirent.name)
if (dirent.isDirectory()) {
yield * getFiles(res)
} else {
yield res
}
}
}
(async () => {
for await (const file of getFiles(inputDir)) {
if (!file.match(/\.md$/)) continue
let contents = await fs.readFile(file, 'utf-8')
const createdMatch = contents?.match(/^created::\s*(.+?)$/m)
const created = createdMatch?.[1]
if (!created) continue
let yaml = `---\ncreated: ${created}\n---\n`
if (contents.match(/^---/s)) {
const yamlMatch = contents?.match(/^---\n(.*?)\n---\r?\n/s)
if (!yamlMatch) {
contents = yaml + contents
} else if (yamlMatch[1].match(/created:/)) {
continue
} else {
yaml = `---\ncreated: ${created}\n${yamlMatch[1]}\n---\n`
contents = contents.replace(yamlMatch[0], yaml)
}
} else {
contents = yaml + contents
}
contents = contents.replace(createdMatch[0], '')
const outfile = file.replace(inputDir, outputDir)
await fs.mkdir(path.dirname(outfile), { recursive: true })
await fs.writeFile(outfile, contents, 'utf8')
console.log('Updating ' + outfile)
}
})()