-
Notifications
You must be signed in to change notification settings - Fork 0
/
httprequestdump.js
68 lines (50 loc) · 1.53 KB
/
httprequestdump.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
'use strict';
let fs = require('fs'),
http = require('http'),
LISTEN_HOSTNAME = '0.0.0.0',
LISTEN_PORT = 9090,
DUMP_FILE_PATH = 'dumpdata.txt',
ACK_HTTP_CODE = 200,
ACK_CONTENT_TYPE = 'text/plain',
ACK_MESSAGE = 'HELLO';
{
let server = http.createServer((request,response) => {
// start of new HTTP request
let requestDataSlabList = [],
httpMethod = request.method.toUpperCase(),
requestURI = request.url;
// summary request details
console.log(`Incoming request\nMethod: ${httpMethod}\nURI: ${requestURI}`);
// wire up request events
request.on('data',(data) => {
// add received data to buffer
requestDataSlabList.push(data);
});
request.on('end',(data) => {
// send response to client
response.writeHead(
ACK_HTTP_CODE,
{'Content-Type': ACK_CONTENT_TYPE}
);
response.end(`${ACK_MESSAGE}\n`);
// write/append received request to file
let headerItemList = [],
dataSlab = requestDataSlabList.join('');
for (let headerItem of Object.keys(request.headers).sort()) {
headerItemList.push(`\t${headerItem}: ${request.headers[headerItem]}`);
}
fs.appendFile(
DUMP_FILE_PATH,
`Method: ${httpMethod}\nURI: ${requestURI}\n` +
`Headers:\n${headerItemList.join('\n')}\n\n${dataSlab}\n\n\n`,
(err) => {
// end of HTTP request
console.log(`End of request, ${dataSlab.length} bytes received.\n`);
}
);
});
});
// start listening server
console.log(`Listening on ${LISTEN_HOSTNAME}:${LISTEN_PORT}\n`);
server.listen(LISTEN_PORT,LISTEN_HOSTNAME);
}