forked from hugomd/parrot.live
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (50 loc) · 1.62 KB
/
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
const fs = require('mz/fs');
const http = require('http');
const {Readable} = require('stream');
const colors = require('colors/safe');
const frames = [];
// Setup frames in memory
fs.readdir('./frames').then(data => {
data.forEach(async frame => {
const f = await fs.readFile(`./frames/${frame}`);
frames.push(f.toString());
})
});
const colorsOptions = ['red', 'yellow', 'green', 'blue', 'magenta', 'cyan', 'white'];
const numColors = colorsOptions.length;
const streamer = stream => {
let index = 0;
let lastColor = -1;
let newColor = 0;
return setInterval(() => {
if (index >= frames.length) index = 0; stream.push('\033[2J\033[H');
newColor = Math.floor(Math.random() * numColors);
// Reroll for a new color if it was the same as last frame
if(newColor == lastColor) {
newColor += (1 + Math.floor(Math.random() * (numColors - 1)));
newColor %= numColors;
}
lastColor = newColor;
stream.push(colors[colorsOptions[newColor]](frames[index]));
index++;
}, 70);
}
const server = http.createServer((req, res) => {
if (req.headers && req.headers['user-agent'] && !req.headers['user-agent'].includes('curl')) {
res.writeHead(302, {'Location': 'https://github.com/hugomd/parrot.live'});
return res.end();
}
const stream = new Readable();
stream._read = function noop () {};
stream.pipe(res);
const interval = streamer(stream);
req.on('close', () => {
stream.destroy();
clearInterval(interval);
});
});
const port = process.env.PARROT_PORT || 3000;
server.listen(port, err => {
if (err) throw err;
console.log(`Listening on locahost:${port}`);
});