-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileserver.js
45 lines (26 loc) · 1.26 KB
/
fileserver.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
var http = require("http");
var fs = require("fs");
var path = require("path");
http.createServer(function(req, res){
console.log(`${req.method} request for ${req.url}`);
if (req.url === "/"){
fs.readFile("./public/index.html", "UTF-8", function(err, html){
res.writeHead(200, {"Content-type": "text/html"});
res.end(html);
});
} else if (req.url.match(/.css$/)) {
var cssPath = path.join(__dirname, 'public', req.url);
var fileStream = fs.createReadStream(cssPath, "UTF-8");
res.writeHead(200, {"Content-type": "text/css"});
fileStream.pipe(res);
} else if (req.url.match(/.jpg$/)) {
var imgPath = path.join(__dirname, 'public', req.url);
var imgStream = fs.createReadStream(imgPath); // img is read in binary
res.writeHead(200, {"Content-Type": "image/jpeg"});
imgStream.pipe(res);
} else {
res.writeHead(404, {"Content-Type": "text/plain"});
res.end("404 File Not Found");
}
}).listen(3000); // we can just chain the listen command on to the end
console.log("File server is running on port 3000");