-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (70 loc) · 2.58 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import express from "express";
import csvtojson from "csvtojson";
import byteSize from "byte-size";
import status from "express-status-monitor";
import { stat } from "node:fs/promises";
import { createReadStream, readFile } from "node:fs";
import { Readable, Transform, Writable } from "node:stream";
import { TransformStream } from "node:stream/web";
import { setTimeout } from "node:timers/promises"
const app = express();
console.log(process.pid); // PRINTING THE PROCESS ID
app.use(status()); // MONITORING THE SERVER STATUS || CHECK ON /status
const fileName = "metadata.csv"; // FILE THAT BE USING | CAN BE OF ANY SIZE | ON ROOT DIRECTORY | CHANGE IT TO YOUR FILE
/**
* HERE WE ARE CONVERTING CSV FILE TO JSON AND THEN MAPPING THE DATA TO A NEW JSON OBJECT
* AND THEN STREAMING THE DATA TO THE CLIENT
*/
app.use(express.static("public"));
// GO TO / TO SEE THE FRONTEND
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "index.html"));
});
app.get("/file-info", async (req, res) => {
try {
const { size } = await stat(fileName);
return res.json({ size: byteSize(size).toString() });
} catch (error) {
return res.json({ size: null });
}
})
app.get("/stream-data", async (req, res) => {
try {
let controller = new AbortController();
req.on("close", () => {
console.log("Client connection closed");
controller.abort();
});
const csvToJsonTransform = csvtojson();
await Readable.toWeb(createReadStream(fileName))
.pipeThrough(Transform.toWeb(csvToJsonTransform))
.pipeThrough(
new TransformStream({
async transform(chunk, controller) {
const decodeChunk = JSON.parse(Buffer.from(chunk));
// MAPPING THE DATA TO A NEW OBJECT | YOU CAN CHANGE IT TO YOUR OWN
const mappedData = {
url: decodeChunk.url,
journal: decodeChunk.journal,
authors: decodeChunk.authors,
cord_uid: decodeChunk.cord_uid,
license: decodeChunk.license,
};
await setTimeout(200); // SIMULATING A DELAY OTHERWISE IT WILL BE TOO FAST AND OUR UI WILL NOT BE ABLE TO HANDLE IT
controller.enqueue(JSON.stringify(mappedData).concat("\n"));
},
})
)
.pipeTo(Writable.toWeb(res), { signal: controller.signal });
} catch (error) {
if (error.name === "AbortError") {
console.log("Stream aborted ");
return;
}
console.log("something happened :( ", error);
}
});
const PORT = 3001;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});