-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_res_obj.js
More file actions
82 lines (65 loc) · 1.81 KB
/
create_res_obj.js
File metadata and controls
82 lines (65 loc) · 1.81 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
75
76
77
78
79
80
81
82
var path = require('path');
var file = require ('./html_file_processing');
var fs = require('fs');
var cap = require('./capitalize');
var CODES = require('./codes.js');
var mime = require('mime');
function create_resp_obj(socket)
{
var response = {header: [], body: "", status: 201},
_sent = false;
const priv = {
sent: () => _sent,
write: body => {
response.body += body;
},
closes: () => {
if (_sent)
return
_sent = true
priv.header('connection', "keep-alive");
priv.header('date', new Date().toGMTString());
// console.log(priv.toString())
// console.log()
socket.write(priv.toString())
socket.end()
},
status: code => (response.status = code),
header: (name, value) => {
response.header[name] = value
},
toString: () => {
const headers = Object.keys(response.header)
.map(key => `${cap.capitalizeEachWord(key)}: ${response.header[key]}`)
.join('\n')
return (`HTTP/1.1 ${response.status} ${CODES[response.status]}
${headers}
${response.body}
`)},
sends: data => {
priv.write(data);
priv.closes();
},
sendJSON: data => {
data = JSON.stringify(data);
priv.header('content-type', 'application/json');
priv.header('content-length', data.length);
priv.sends(data);
},
sendFile: path => {
var date;
var file_type;
var today;
var stats
stats = fs.statSync(path);
date = new Date();
today = date.toGMTString();
file_type = mime.lookup(path);
priv.header('content-type', file_type);
priv.header('content-length', stats["size"]);
priv.sends(fs.readFileSync(path, 'binary'));
}
}
return priv;
}
module.exports = create_resp_obj;