Serve a Static HTML File with NodeJS
- January 18th, 2011
- By David Granado
- Write comment
So, I posed a question onto StackOverflow today and got some really good advice. My question was this: how do I server a simple static HTML file from Node.js. I’m not a fan of doing this:
response.write("...<p>blahblahblah</p>...");
From most, the answer was “use
Express.js“. That’s good advice if you just want to get the job done. However, I think the point was lost.
In this particular instance, I wanted to have at least a superficial understanding of the mechanics of what’s going on underneath the pretty interfaces of the framework.
Anywho, here’s one way of doing it given a file ‘index.html’ in the same directory:
var sys = require('sys'),
http = require('http'),
fs = require('fs'),
index;
fs.readFile('./index.html', function (err, data) {
if (err) {
throw err;
}
index = data;
});
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(index);
response.close();
}).listen(8000);
Nothing fancy. Just open the file, store the contents, and puke it back up on every request.
If there is a more elegant way of handing this extremely simple use-case utilizing only core libraries, feel free to share it on the StackOverflow post.