forked from XueCai-at/nodejs_performance
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
74 lines (65 loc) · 2.08 KB
/
app.js
File metadata and controls
74 lines (65 loc) · 2.08 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
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
import express from "express";
//////////////////////////////// Web app ////////////////////////////////
const app = express();
const bigObject = makeBigObject(2000, 2);
// const bigObject = makeBigObject(24, 2); // < 8K
let requestCount = 0;
let firstRequestStartTime;
function getTimeMs() {
return elapsedMsSince(firstRequestStartTime);
}
async function requestHandler({ requestIndex, req, res }) {
if (!firstRequestStartTime) {
firstRequestStartTime = process.hrtime.bigint();
}
console.log(
`[${getTimeMs()}] Serializing response for request ${requestIndex}...`
);
const serializedBigObject = JSON.stringify(bigObject);
const flushStartTime = process.hrtime.bigint();
res.on("finish", () => {
const flushDurationMs = elapsedMsSince(flushStartTime);
console.log(
`[${getTimeMs()}] -- Took ${flushDurationMs}ms to flush response for request ${requestIndex} --`
);
});
console.log(
`[${getTimeMs()}] Sending ${getReadableString(serializedBigObject.length)} response for request ${requestIndex}...`
);
res.send(serializedBigObject);
console.log(`[${getTimeMs()}] - Handler done for request ${requestIndex} -`);
}
app.get("/", async (req, res) => {
const requestIndex = ++requestCount;
requestHandler({ requestIndex, req, res });
});
app.listen("/tmp/sock", () =>
console.log(`Example app listening on Unix domain socket /tmp/sock!`)
);
//////////////////////////////// Utils below ////////////////////////////////
function makeBigObject(leaves, depth) {
if (depth === 0) {
return "howdy";
} else {
const ret = {};
for (let i = 0; i < leaves; ++i) {
ret[i] = makeBigObject(leaves, depth - 1);
}
return ret;
}
}
function elapsedMsSince(start) {
return elapsedMsBetween(start, process.hrtime.bigint());
}
function elapsedMsBetween(start, end) {
return Math.round(Number(end - start) / 1e6);
}
function getReadableString(length) {
if (length >= 1024 * 1024) {
return `${Math.round(length / 1024 / 1024)}MB`;
} else if (length >= 1024) {
return `${Math.round(length / 1024)}KB`;
} else {
return `${length}B`;
}
}