Last active
August 1, 2018 17:21
-
-
Save brbcoding/13a873a752065748463763536efdf5ed to your computer and use it in GitHub Desktop.
Add first image to frontmatter, replace youtube links with media embed components
This file contains hidden or 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') | |
const FOLDER = './_posts' | |
fs.readdir(FOLDER, (err, files) => { | |
if (err) return console.error(err) | |
files.forEach(file => { | |
const filepath = `${FOLDER}/${file}` | |
if(path.extname(file) != '.md') return console.log(`${file} not markdown, passing`) | |
fs.readFile(filepath, 'utf8', (err, content) => { | |
const len = content.length | |
if(err) return console.error(err) | |
// check for thumbnails | |
if(content.match(/thumbnail:/)) { | |
// console.log(`${filepath} already has a thumbnail`) | |
} else { | |
const matches = content.match(/(?:!\[(.*?)\]\((.*?)\))/g) | |
const image = matches ? matches[0].replace(/\!\[.*\]\(/, '').replace(/\)$/, '') : null | |
if(image != null) { | |
const title = content.match(/title:.*\n/) | |
content = `${content.slice(0, title.index)}thumbnail: ${image}\n${content.slice(title.index)}` | |
} | |
} | |
if(content.match(/youtube/)) { | |
let result = content.match(/(<(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+)/i) | |
if(result) { | |
const url = result[0].replace(/<(.*)>.*/, '$1') | |
content = `${content.slice(0, result.index)}<media-embed src='${url}'></media-embed>${content.slice(result.index + result[0].length)}` | |
} | |
} | |
fs.writeFile(`${filepath}`, content, 'utf8', err => { | |
if(err) console.error(err) | |
}) | |
}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment