Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created September 27, 2022 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoisryosuke/31cbdd1dae773d60e64004cda0812403 to your computer and use it in GitHub Desktop.
Save whoisryosuke/31cbdd1dae773d60e64004cda0812403 to your computer and use it in GitHub Desktop.
NodeJS - Parse MD/MDX files and copy images to another folder (blog migration script) - run using `node export.js`
const fs = require('fs')
const path = require('path')
// Loop through all years
// Go into each folder
// Get MDX file
// Add template to frontmatter
// layout: "@/layouts/BlogLayout.astro"
// Found images in folder with MDX?
// Copy images to public/blog/YEAR folder
const ROOT = './content/blog/'
const IMAGE_ROOT = './images/'
const years = fs.readdirSync(path.join(ROOT))
years.forEach((year) => {
const blogPostFolders = fs.readdirSync(path.join(ROOT, year))
// Go into each folder
blogPostFolders.forEach((blogPostFolder) => {
const blogImagePath = path.join(IMAGE_ROOT, year)
const blogPostFolderContents = fs.readdirSync(
path.join(ROOT, year, blogPostFolder)
)
// Create folder if it doesn't exist
if (!fs.existsSync(blogImagePath)) {
fs.mkdirSync(blogImagePath)
}
blogPostFolderContents.forEach((file) => {
const filePath = path.join(ROOT, year, blogPostFolder, file)
const copyPath = path.join(IMAGE_ROOT, year, file)
// Get MDX file
// Add template to frontmatter
// layout: "@/layouts/BlogLayout.astro"
if (file.includes('.md')) {
const blogPostMdx = fs.readFileSync(filePath, 'utf-8')
console.log('mdx', blogPostMdx)
// Find frontmatter closing tag (second `---`)
const splitPost = blogPostMdx.split('---')
console.log()
splitPost[1] = `${splitPost[1]}
layout: "@/layouts/BlogLayout.astro"
`
const joinPost = splitPost.join('---')
// Save post
// fs.writeFileSync(filePath, joinPost)
}
if (
file.includes('.png') ||
file.includes('.jpg') ||
file.includes('.jpeg') ||
file.includes('.gif') ||
file.includes('.svg')
) {
fs.copyFileSync(filePath, copyPath)
fs.rmSync(filePath)
}
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment