Files
  • index.js
  • bin
  • essays
  • lib
  • pages
  • public
  • .eslintrc.json
  • package-lock.json
  • package.json
  • scratch.json
  • yarn.lock
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
const express = require('express');
const renderPage = require('./lib/renderPage');
const marked = require('marked');
const path = require('path');
const app = express();
const fs = require('fs');
const hljs = require('highlight.js');
const _ = require('lodash');
const { Feed } = require('feed');

const renderer = new marked.Renderer();

// Pass html unescaped
renderer.html = str => _.unescape(str);

marked.setOptions({
  renderer: renderer,
  highlight(code, lang) {
    try {
      return hljs.highlight(code, lang).value;
    } catch (e) {
      // Failed to highlight the language
      return hljs.highlightAuto(code).value;
    }
  },
});

const staticOpts = {
  maxAge: 365 * 24 * 60 * 60 * 1000,
};

app.use('/public', express.static(
  path.join(__dirname, 'public'), staticOpts
));

const essaysDir = path.join(__dirname, 'essays');

function parse(fpath) {
  const post = fs.readFileSync(path.join(essaysDir, fpath), 'utf8');
  const parts = post.split('---\n');
  const json = parts.shift();
  const essay = (() => {
    try {
      return JSON.parse(json);
    } catch (e) {
      console.error('error parsing json for essay', fpath);
      throw e;
    }
  })();

  const date = Date.parse(essay.date);
  if (isNaN(date)) {
    throw new Error(`Invalid date: ${essay.date} - ${fpath}`);
  }
  essay.date = new Date(date);
  essay.raw = parts.join('---\n');
  essay.content = marked(essay.raw);
  essay.url = path.basename(fpath, '.md');
  essay.description = essay.raw.slice(0, 200).replace(/\n/g, ' ') + '...';
  return essay;
}

const essays = fs.readdirSync(essaysDir)
  .filter(fpath => fpath[0] !== '.')
  .map(parse)
  .sort((a, b) => b.date - a.date);

const feed = new Feed({
  title: "Amjad Masad",
  description: "Essays",
  id: "https://amasad.me",
  link: "https://amasad.me",
  image: "https://www.gravatar.com/avatar/03637ef1a5121222c8db0ed48c34e124.png?s=200",
  favicon: "https://www.gravatar.com/avatar/03637ef1a5121222c8db0ed48c34e124.png?s=200",
  copyright: "All rights reserved 2019, Amjad Masad",
  generator: "amasad.me",
  feedLinks: {
    json: "https://amasad.me/json",
    rss: "https://amasad.me/rss"
  },
  author: {
    name: "Amjad Masad",
    email: "[email protected]",
    link: "https://amasad.me"
  }
});

for (const essay of essays) {
  feed.addItem({
    title: essay.title,
    id: essay.id,
    url: `https://amasad.me/${essay.url}`,
    description: essay.description,
    content: essay.content,
    date: essay.date,
    image: essay.image,
    author: [
      {
        name: "Amjad Masad",
        email: "[email protected]",
        link: "https://amasad.me"
      },
    ],
  });
}

feed.addCategory("Tech");

app.get('/json', (req, res) => {
  res.end(feed.json1());
});

app.get('/rss', (req, res) => {
  res.end(feed.rss2());
});

app.get('/', (req, res) => {
  const essayList = essays.filter(es => !es.hidden).map(es => (
    `<li>
       <a href="${es.url}">${es.title}</a>
     </li>`
  )).join('\n');

  const html = `
  <article class="index postContent">
    <nav>
      <a href="/about">About</a>
      <a href="https://twitter.com/amasad">Twitter</a>
      <a href="https://github.com/amasad">Github</a>
      <a href="https://amasad.me/rss">RSS</a>
    </nav>
    <div class="essayList">
      Essays:
      <ul>
        ${essayList}
      </ul>
    </div>
  </article>
  `;
  const page = renderPage({}, html);
  res.send(page);
});

essays.forEach((es) => {
  app.get(`/${es.url}`, (req, res) => {
    const html = `
        <article class="postItem">
          <h1 class="postTitle">
            <a href="/${es.url}">${es.title}</a>
          </h1>
          <h3 class="postAuthor">
            ${es.date.toDateString()}
          </h3>
          <div class="postContent">
            ${es.content}
          </div>
        </article>
        `;

    const page = renderPage({
      title: es.title,
      description: es.description,
      url: `/${es.url}`,
      image: es.image,
    }, html);
    res.send(page);
  });
});

app.get('/about', (req, res) => {
  fs.readFile(
    path.join(__dirname, 'pages', 'about.md'),
    (err, d) => {
      if (err) {
        res.status(500);
        res.text('something went wrong :(');
        return;
      }

      res.set('Content-Type', 'text/html');
      const content = marked(d.toString('utf8'));
      const html = `<article class="postItem postContent">
      ${content}
      </article>`;

      const page = renderPage({}, html);
      res.send(page);
    }
  );
});

const redirections = {
  '/2012/12/11/stuffjs': '/stuffjs',
  '/2016/04/14/kierkegaard-and-entrepreneurship': '/kierkegaard',
  '/2015/04/09/hello-world': '/hello-world',
  '/2016/03/05/caching-and-promises': '/caching-promises',
  '/2012/07/17/on-vms-in-javascript': '/js-vms',
  '/2016/01/17/eval-as-a-service': '/eval-as-a-service',
  '/2016/01/03/overcoming-intuition-in-programming': '/intuition',
  '/2016/03/09/john-carmack-on-idea-generation': '/carmack',
  '/2012/07/02/the-dark-side-of-functionprototypebind': '/bind',
  '/2016/01/13/the-stoic-of-open-source': '/stoic-oss',
  '/2014/03/09/lesser-known-javascript-debugging-techniques': '/debugging',
  '/2014/03/16/why-im-excited-about-objectobserve': '/object-observe',
  '/2015/10/31/javascript-async-functions-for-easier-concurrent-programming':
    '/async-js',
  '/2016/03/13/what-is-perfectionism-and-how-to-cure-it': '/perfectionism',
  '/2014/01/18/introducing-waraby-mobile-optimized-arabic-search-web-app':
    '/waraby',
  '/2014/01/10/implementing-bret-victors-learnable-programming-has-never-been-easier': '/learnable',
  '/2014/01/06/building-an-in-browser-javascript-vm-and-debugger-using-generators': '/js-debugger',
};

Object.keys(redirections).forEach((key) => {
  const route = redirections[key];
  app.get(key, (req, res) => {
    res.redirect(301, route);
  });
});

const port = process.env.PORT || 8000;
app.listen(port, () => {
  console.log('running on port', port);
});
node v9.7.1 linux/amd64