Moving Dataview inline 'created' date to be frontmatter property

Moving Dataview inline 'created' date to be frontmatter property

Published with Share Note 🔸 Part of Obsidian guides
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)) {
      // This is YAML formatted - insert / update the existing format
      const yamlMatch = contents?.match(/^---\n(.*?)\n---\r?\n/s)
      if (!yamlMatch) {
        // Use the blank/standard YAML
        contents = yaml + contents
      } else if (yamlMatch[1].match(/created:/)) {
        // There's already a created YAML tag, nothing to do
        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)
  }
})()
Share Note for Obsidian 🌓