Skip to content

Instantly share code, notes, and snippets.

@dewcked
Created December 12, 2021 12:28
Show Gist options
  • Save dewcked/8b9f0982acfdca846af88021d41fc813 to your computer and use it in GitHub Desktop.
Save dewcked/8b9f0982acfdca846af88021d41fc813 to your computer and use it in GitHub Desktop.
Script for transporting yaml-markdown into compatible svelte route directory files.
import { parse } from 'marked';
import fs from 'fs';
import { promisify } from 'util';
import { resolve } from 'path';
const readdir = promisify(fs.readdir);
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const access = promisify(fs.access);
const mkdir = promisify(fs.mkdir);
const inputdir = 'put-posts-here/'
const outputdir = 'posts/'
const sveltedir = 'src/routes/posts/'
const tags = { 'title': 'title', 'category': 'category' };
const optional_tags = { 'series': 'series', 'page': -1 };
function isMarkdown(filename) {
return new Promise(function (resolve, reject) {
resolve(filename.slice(filename.length - 3, filename.length) === '.md' ? true : false);
});
}
async function writeFiles(outputdir, filename, content) {
try {
try {
await access(outputdir);
} catch (err) {
await mkdir(outputdir, { recursive: true });
}
await writeFile(outputdir + filename, content);
console.log('[Post] Posted ' + filename);
resolve();
} catch (err) {
console.log('Error', err);
}
};
// Code form Node.js in action
function move(oldPath, newPath, callback) {
rename(oldPath, newPath, function (err) {
if (err) {
if (err.code === 'EXDEV') {
copy();
} else {
callback(err);
}
return;
}
callback();
});
function copy() {
var readStream = createReadStream(oldPath);
var writeStream = createWriteStream(newPath);
readStream.on('error', callback);
writeStream.on('error', callback);
readStream.on('close', function () {
unlink(oldPath, callback);
});
readStream.pipe(writeStream);
}
}
function processFrontMatter(document, tags, optional_tags) {
let components = document.split(/---[\n\s]*/, 3); // Seperate Yaml front matter and Content part
let metas = components[1].replace(/\s*\n\s*/, '\n').split('\n', Object.keys(tags).length + Object.keys(optional_tags).length); // Divide each meta tags
let data = {};
data['content'] = components[2].replace(/[\s\n\r]*/, '');
for (let meta in metas) {
let tag = metas[meta].split(/\s*:\s*/, 2);
if (tag == '') {
continue;
}
if (tags[tag[0]] == undefined) {
if (optional_tags[tag[0]] == undefined) {
console.log('tag ' + tag[0] + ' is not valid. check syntax or add ' + tag[0] + ' to either \'tags\' or \'optional_tags\'');
data = {};
break;
}
} else {
delete tags[tag[0]];
}
data[tag[0]] = JSON.parse(tag[1]);
}
if (Object.keys(tags).length != 0) {
for (tag in Object.keys(tags)) {
console.log(key + 'must be defined. or remove ' + key + ' from \'tags\'');
}
data = {};
}
return new Promise(function (resolve, reject) {
resolve(data);
});
}
async function processMarkDown(inputdir, outputdir, sveltedir, tags, optional_tags) {
try {
let filenames = await readdir(inputdir);
for (let i in filenames) {
if (await isMarkdown(filenames[i])) {
let document = await readFile(inputdir + filenames[i], 'utf-8');
let data = await processFrontMatter(document, JSON.parse(JSON.stringify(tags)), optional_tags);
if (data['series'] != undefined) {
await writeFiles(sveltedir + data['category'] + '/' + data['series'] + '/'
, data['page'] + '-' + filenames[i].slice(0, filenames[i].length - 2) + 'svelte'
, parse(data['content']).replace(/{/g, '{').replace(/}/g, '}'));
} else {
await writeFiles(sveltedir + data['category'] + '/'
, filenames[i].slice(0, filenames[i].length - 2) + 'svelte'
, parse(data['content']).replace(/{/g, '{').replace(/}/g, '}'));
}
move(inputdir + filenames[i], outputdir + filenames[i], function (err) { if (err) throw err; });
}
}
} catch (err) {
console.log('Error', err);
}
}
console.log(JSON.parse('"category"'));
processMarkDown(inputdir, outputdir, sveltedir, tags, optional_tags);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment