NodeJS - Parse MD/MDX files and copy images to another folder (blog migration script) - run using `node export.js`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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