On my local machine, I want to deploy static Web pages (containing HTML, CSS, JS files) on Node, without using any framework (e.g., Express). I did put the Web page related files into the public folder, and then call the index.html, by using the fs library in node, as the following:
var http = require('http'), fs = require('fs');
fs.readFile('./public/index.html', function (err, html) {
if (err) { throw err;}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html); response.end();
}).listen(1337, '127.0.0.1');;
});
I used CURL and all the files (HTML, CSS, JS) are in fact deployed on the localhost. However, when I go to the port 1337 on the localhost, it shows the HTML contents but doesn't show the behavior, written in JS, imported in the index.html.
Your index.html file is making a separate request to index.js
(or whatever the JS file is / files are). Your server will handle every response the same way: serve the contents of the index.html
file.
Creating a server in this way does not automatically server files from the file system like other servers such as Apache might. Instead, you would need to do something like:
http.createServer(function(request, response) {
if (request.url == "/index.html" || request.url == "/") {
response.writeHeader(200, {"Content-Type": "text/html"});
fs.createReadStream("./public/index.html").pipe(response);
}
else if (request.url == "/index.js") {
response.writeHeader(200, {"Content-Type": "text/javascript"});
fs.createReadStream("./public/index.js").pipe(response);
}
}).listen(1337, '127.0.0.1');
Of course writing a route for each file in the file system that you want to serve is probably pretty silly. You could use a static file server module, or implement a static file server yourself. This would involve checking the file system based on the request URL and then serving the file with the correct content type which you can look up using a module like mime
.