-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimestamp.js
executable file
·62 lines (52 loc) · 1.46 KB
/
timestamp.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
#! /usr/bin/env nodejs
'use strict';
const path = require('path');
const url = require('url');
const http = require('http');
const fs = require('fs');
if (process.argv.length !== 3) {
process.stderr.write(`usage: ${path.basename(process.argv[1])} port\n`);
process.exit(1);
}
const sendResponse = (r, data) => {
r.writeHead(200, { 'content-type': 'application/json' });
r.write(JSON.stringify(data));
r.end();
};
const server = http.createServer((req, res) => {
// parse the url
const URL = url.parse(req.url, true);
if (URL.pathname === '/') {
res.writeHead(200, { 'content-type': 'text/html' });
fs.createReadStream('./index.html').pipe(res);
} else {
console.log(URL);
let api = URL.pathname.replace(/^\//, '');
api = decodeURI(api);
// get the time stamp
let timestamp;
if (/^\d+$/.test(api)) {
// unix time -> seconds but javascript Date-> milliseconds
timestamp = parseInt(api, 10) * 1000;
} else {
timestamp = Date.parse(api);
}
const payload = {};
// check if valid time
if (Number.isNaN(timestamp)) {
payload.unix = null;
payload.natural = null;
} else {
// build pay load
const date = new Date(timestamp);
payload.unix = date.getTime() / 1000;
payload.natural = date.toLocaleString('en', {
month: 'long',
day: '2-digit',
year: 'numeric',
});
}
sendResponse(res, payload);
}
});
server.listen(process.argv[2]);