I am trying to write a node js server that gives back whatever the user requested, if the resource is in the file system.
For example, if the request URL were /index.html
, it would try to find a file called 'index.html' in the root directory and respond with a stream to that file. If the request were /myscript.js
, it would do the same, finding a file called myscript.js
and piping that to the response.
Here is what I have so far:
var http = require("http");
var fs = require("fs");
var port = process.env.PORT || 3000;
http.createServer(function (request, response) {
if (request.method == "GET") {
console.log(request.url);
if (request.url == "/") { // if the url is "/", respond with the home page
response.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream("index.html").pipe(response);
} else if (fs.existsSync("." + request.url)) {
response.writeHead(200/*, {"Content-Type": request.headers['content-type']}*/);
fs.createReadStream("." + request.url).pipe(response);
} else {
response.writeHead(404, {"Content-Type": "text/plain"});
response.end("404 Not Found");
}
} else {
response.writeHead(404, {"Content-Type": "text/plain"});
response.end("404 Not Found");
}
}).listen(port);
// Console will print the message
console.log('Server running at http://127.0.0.1:' + port +'/');
There are a few things that I don't like about this code:
fs
thinks that whenever the path starts with /
, the file does not exist, so I must add a .
before the file path. See line 10 and 12. Will this always work? I feel like this is a really bad trick to work around the problem. Addressing your two bullet points:
.
when using fs
because fs
will look at the root directory of your system otherwise. Remember, the system root is different than your server root. path.extname
and then a switch
statement to set the content type like so. The code below is taken from an blog post I wrote on how to set up a simple static server using Node without Express:
let filePath = `.${request.url}`; // ./path/to/file.ext
let ext = path.extname(filePath); // .ext
let contentType = 'application/octet-stream'; // default content type
if(ext === '') {
filePath = './index.html'; // serve index.html
ext = '.html';
}
switch (ext) {
case '.html':
contentType = 'text/html';
break;
case '.css':
contentType = 'text/css';
break;
case 'js':
contentType = 'text/javascript';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.