Serve a Static HTML File with NodeJS
- January 18th, 2011
- Posted in Programming . Tutorials
- 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.
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
thanks for the code snippet. I was looking for something similar to understand the basics of nodejs.
BTW, have you figured out how to redirect requests to correct handlers? For example how do I make ‘about.js’ to handle ‘http://localhost/about‘ request?
rebayeet – the request object passed into the anonymous function that creates the server contains the url that was requested. You can either parse that url or install some routing middleware to handle that for you… although I’d recommend using the express framework to handle that kind of stuff.