forked from Spoorthya/fundstarter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (59 loc) · 1.98 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
var http = require('http');
var fs = require('fs');
var port = process.env.PORT || 80;
/******************************* PART 1A ***********************************/
// part 1b
var readSyncHTML = function() {
return fs.readFileSync("./index.html", "utf8");
}
// part 1b
var listener_a = function(req, res) {
res.end(readSyncHTML());
}
var server_a = http.createServer(listener_a);
//server_a.listen(port);
/************************** END of PART 1A ********************************/
/*************************** PART 1B *************************************/
var readHTML = function(callback) {
fs.readFile("./index.html", "utf8", function(err, content) {
if (err) return callback(err);
callback(null, content);
});
}
var listener_b = function(req, res) {
readHTML(function(err, content) {
res.writeHead(200);
res.end(content);
});
}
var server_b = http.createServer(listener_b);
//server_b.listen(port);
/**************************** END of PART 1B *******************************/
/*************************** PART 2 - fs.open() ****************************/
var openHTML = function(callback) {
var file = "./index.html";
fs.exists(file, function(exists) {
if (!exists) return callback("File not found:" + file);
fs.stat(file, function(statErr, stats) {
if (statErr) return callback(statErr);
fs.open("./index.html", "r", function(openErr, fd) {
if (openErr) return callback(openErr);
var buff = new Buffer(stats.size);
fs.read(fd, buff, 0, buff.length, null, function(readErr, bytesRead, readBuff) {
var content = readBuff.toString("utf8", 0, readBuff.length);
callback(readErr, content);
fs.close(fd);
});
});
});
});
}
var listener_2_open = function(req, res) {
openHTML(function(err, content) {
res.writeHead(200);
res.end(content);
});
}
var server_2_open = http.createServer(listener_2_open);
server_2_open.listen(port);
/*************************** PART 2 - end fs.open() ***********************/