Skip to content
Example code snippets for blogging platform I made
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.

Files

Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
LICENSE
README.md

README.md

Intro

There are many ways to create blogging sites. The most important factors are automation and clean code. The system I use renders each post and creates a json endpoint that contains my posts.

I use a mix of html and javascript on both the front end and back end

🛠 Tools used: Nodejs, EJS, Express

Post Syntax

All posts have their own file. Each file contains metadata specific to that post.

(Front End) posts/cat.js

module.exports = {
    slug: 'cat', // example.com/post/cat
    date: new Date('01/31/2020'), // date object
    title: 'Here is a cat', 
    image: 'https://example.com/cat.jpg', // direct link to cover image
    html: `
    <p>Here is a cat</p>
    <br>
    <img src="https://example.com/cat.jpg">
    ` // html that will be inserted into post
};

Start Feed.json

Feed JSON is a better and simple alternative to RSS XML

It is also used to grab our posts from the front end

(Back End) app.js

var feed = {
    version: 'https://jsonfeed.org/version/1',
    title: 'My Posts',
    home_page_url: 'https://example.com',
    feed_url: 'https://example.com/feed.json',
    icon: 'https://example.com/avatar.jpg',
    author: {
        name: 'Joe Smith',
        avatar: 'https://example.com/avatar.jpg'
    },
    items: []
};

Load Posts and Finish Feed.json

(Back End) app.js

var express = require('express');
var strip = require('common-tags').stripIndents;

var app = express();

app.posts = []; // Start as empty object
fs.readdirSync('./posts').forEach(file => {
    try {
        var post = require(`./posts/${file}`);
        feed.items.push({
            id: post.slug,
            url: `https://example.com/post/${post.slug}`,
            title: post.title,
            content_html: strip`${post.html}`,
            image: post.image,
            date_published: post.date
        });
        app.posts.push(post);
        console.log(`✔️ Loaded Post: ${file}`);
    } catch (e) {
        console.log(`❌ Couldn't Load: ${file}`);
        console.log(e);
    };
});

// Sort posts by date published and create endpoint
feed.items = feed.items.sort((a, b) => b.date_published - a.date_published);
app.get('/feed.json', (req, res) => res.json(feed));

Feed Endpoint

This allows the front end to get all the posts

(Front End) feed.json

{
    "version": "https://jsonfeed.org/version/1",
    "title": "My Posts",
    "home_page_url": "https://example.com",
    "feed_url: "https://example.com/feed.json",
    "icon": "https://example.com/avatar.jpg",
    "author": {
        "name": "Joe Smith",
        "avatar: "https://example.com/avatar.jpg"
    },
    "items": [
        {
            "id": "cat",
            "url": "https://example.com/post/cat",
            "title": "Here is a cat",
            "content_html": "<p>Here is a cat</p><br><img src=\"https://example.com/cat.jpg\">,
            "image": "https://example.com/cat.jpg",
            "date_published": "2020-01-29T00:00:00.000Z"
        }
    ]
}

Loader

On the front end we can use this feed endpoint to get our posts

(Front End) loader.js

var feed = new XMLHttpRequest();

feed.onload = () => {
    if (feed.status >= 200 && feed.status < 300) {
        var data = JSON.parse(feed.response);
            var post = data.items[0]; // First post
            console.log(`Title: ${post.title}`);
            console.log(`Date: ${post.date_published}`);
            console.log(`Image: ${post.image}`);
            console.log(`Url: ${post.url}`);
        };
    } else {
        console.error('The request failed!');
    };
};

feed.open('GET', 'https://example.com/feed.json');
feed.send();

Rendering with EJS

EJS is a templating engine and can be passed javascript objects

(Back End) app.js

app.set('view engine', 'ejs');

(Back End) routes/post.js

module.exports = app => {
    app.get('/post/:slug', (req, res) => {
        try {
            var post = app.posts.find(p => p.slug === req.params.slug);
            if (!req.params.slug || !post) {
                res.render('blank', {
                    desc: `Couldn't find: ${req.path}`,
                    title: 'Error 404',
                    pagetitle: '404',
                    pagedesc: `Couldn\'t find: ${req.path}`,
                    link: 'https://andre.gg/',
                    linkname: 'Home',
                    linktarget: '_self'
                });
            } else {
                res.render('post', {
                    title: post.title,
                    date: app.tools.formatDate(post.date),
                    image: post.image,
                    html: post.html,
                    slug: req.params.slug,
                });
            };
        } catch (e) {
            console.error(e);
        };
    });
};

(Back End) views/post.ejs

<!DOCTYPE html>
<html>
    <head>
        <title><%=title%></title>
    </head>
    <body>
        <p><%=date%></p>
        <p><%=slug%></p>
        <div><%-html%></div>
        <img src="<%=image%>">
    </body>
</html>
You can’t perform that action at this time.