-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseReq.js
42 lines (37 loc) · 834 Bytes
/
parseReq.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
function parseStartLine (req) {
req = req.split('\r\n')
let startLine = req[0]
startLine = startLine.split(' ')
return [startLine, req.slice(1)]
}
function parseHeader (req) {
let header = {}
let field = []
while (req.length) {
field = req[0].split(/:(.+)/)
header[field[0]] = field[1]
req = req.slice(1)
}
return header
}
function parseBody (req, contentLength) {
let body = ''
while (contentLength > 0) {
body += req[0]
req = req.slice(1)
contentLength--
}
return body
}
module.exports = (request) => {
request = request.split('\r\n\r\n')
const reqStart = parseStartLine(request[0])
const startLine = reqStart[0]
const header = parseHeader(reqStart[1])
const body = parseBody(request[1], header['Content-Length'])
return {
startLine,
header,
body
}
}