-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
43 lines (37 loc) · 1.09 KB
/
server.js
File metadata and controls
43 lines (37 loc) · 1.09 KB
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
const http = require("http");
const fs = require("fs");
const path = require("path");
const axios = require("axios");
function formatMessage(price) {
const date = new Date();
const timeNowStr = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
return `1 BTC cost $${Number(price).toFixed(2)} at ${timeNowStr}`;
}
function send(res) {
res.setHeader("Content-Type", "text/event-stream");
setInterval(() => {
axios("https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT")
.then((response) => {
const { price } = response.data;
if (price) {
res.write(`data: ${formatMessage(price)}\n\n`);
}
})
.catch((error) => {
console.log(error);
});
}, 5000);
}
http
.createServer((req, res) => {
const url = new URL(`http://${req.headers.host}${req.url}`);
if (url.pathname === "/stream") {
send(res);
return;
}
const fileStream = fs.createReadStream(path.join(__dirname, "index.html"));
fileStream.pipe(res);
})
.listen(9000, () => {
console.log("Server started on 9000");
});