repl.it
@turbio/

replit blog

Nodejs

the Repl.it blog

fork
loading
Files
  • index.js
  • posts
  • static
  • views
  • new_post.js
  • posts.json
  • Packager files
  • package-lock.json
  • package.json
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const express = require('express');
const marked = require('marked');
const fs = require('fs').promises;
const path = require('path');
const moment = require('moment');
const hljs = require('highlight.js');

require('ejs');

marked.setOptions({
  renderer: new marked.Renderer(),
  highlight:  function(code, lang) {
	return hljs.highlightAuto(code, [lang]).value;
  },
});

const postPreviews = async () => {
	const buff = await fs.readFile('./posts.json', 'utf8');
	const posts = JSON.parse(buff);

	for (const post of posts) {
		post.content = await renderMarkdown(
			post.url,
			true,
		);
		post.snipped = true;
	}

	return posts;
}

const getPost = async (slug) => {
	const buff = await fs.readFile('./posts.json', 'utf8');
	const post = JSON.parse(buff)
		.find(p => p.url === slug);
	const content = await renderMarkdown(slug);

	return {
		content,
		snipped: false,
		...post,
	}
}

const renderMarkdown = async (slug, snip=false) => {
	const p = path.join(__dirname, 'posts', slug) + '.md'

	let raw = await fs.readFile(p, 'utf8');

	if (snip) {
		const ender = raw.indexOf('[](preview end)');
		if (ender !== -1) {
			raw = raw.slice(0, ender);
		} else {
			const nlnl = raw.indexOf('\n\n');
			if (nlnl !== -1) {
				raw = raw.slice(0, nlnl);
			}
		}
	}

	// try to resolve absolute links back to repl.it
	raw = raw.replace(/(\]\()(\/.+\))/g, '$1https://repl.it$2');

	return marked(raw);
}


const errPage = (res, err) => {
	res.locals.err = err;
	res.render('error.ejs')
}

const app = express();

app.use(express.static('static'))

app.get('/', (req, res) => {
	postPreviews()
		.then(p => {
			res.locals.posts = p;
			res.locals.moment = moment;
			res.render('index.ejs');
		})
		.catch(err => errPage(res, err));
});

app.get('/:slug', (req, res) => {
	const { slug } = req.params;

	getPost(slug)
		.then(post => {
			res.locals.post = post;
			res.locals.moment = moment;
			res.render('post-page.ejs');
		})
		.catch(err => errPage(res, err));
});

app.listen(3000, () => { console.log('blog is running'); });
Fetching token
?