I am just starting out with node.js and am trying to serve a static index.html file, which of course loads CSS, JS, and images. I have tried by reading the index.html file both by using fs.readFile and with node-static's serveFile.
Both serve the file, but then it cannot find the included CSS, JS, and images. Perhaps it is my paths that are wrong, but here is my directory structure.
I have used relative paths to these referenced files from the index.html file. So simply css/main.css. Also, in case they needed to be relative to the server.js file, I did ../css/main.css. And finally in case the path needed to be absolute and the index.html directory was root, so /css/main.css. Nothing is loaded.
What am I doing wrong?
var http = require('http'),
fs = require('fs');
fs.readFile('../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(8080);
});
This serves the file fine.
As I say, I'm still learning.
The node-static 'API' is not very thorough so I reverted back the above route.
Thanks.
With the server you created above, you're sending the contents of the HTML file for every request - even if the request was for an image or css file. You have to inspect the request object coming in to see what the user is asking for, then send the appropriate file and set the appropriate content-type.
Or, you could make you're life much easier and use Express http://expressjs.com
Express handles most of this stuff for you, including a static file server.
My friend, do not waste your own time on re-inventing the wheel.
Use the Express framework which is very comfortable as far as I can tell, AND handles these things easily.
The problem is the content-type that you are returning. Take a look at this example for the most common content-types:
If you must do it yourself (rather than use Express) you can this module to map most MIME types.