Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Correct way to Load JS Files With HTML files through NodeJS

Correct way to Load JS Files With HTML files through NodeJS


I cant get the contents included in the head of the served defualt.htm page to "work". The html loads in the dom, just the CSS and JS files fail. Is there a better alternative? Id like to keep the solution within NodeJS but alternatively open to and express as well.

Thanks, below is what im using.

NodeJS Serving the Page

var http = require('http'),
fs = require('fs');

fs.readFile(__dirname+'/default.htm', function (err, html) {
    if (err) {
        throw err; 
    http.createServer(function(request, response) {  
        response.writeHeader(200, {"Content-Type": "text/html"});  

Default.html Page

Problem courtesy of: sia


I'm going to throw my two cents in here as well.

The way I solved the same problem with serving static files is that I started using the Paperboy module, which is deprecated in favor of the Send module nowadays.

Anyhoo, the way I solved it was to "hijack" the request before it went into my GET method and check the path of it.

The way I "hijack it" is as follows

self.preProcess(self, request, response);


preProcess: function onRequest(app, request, response){ //DO STUFF }

If the path contained the STATICFILES dir, I would do a diffrent serving of files otherwise I'd go with the "html"-path. Below is the //DO STUFF of the preProcess() function

var path = urllib.parse(request.url).pathname;
if(path.indexOf(settings.STATICFILES_DIR) != -1) {
    path = settings.STATICFILES_DIR;
    requestedFile = request.url.substring(request.url.lastIndexOf('/') + 1, request.url.length);
    return resolver.resolveResourceOr404(requestedFile, request, response);

There might be a better way of doing this but this works like a charm for the things that I need it to do.

Using the Paperboy module I then, using the resolver.resolveResourceOr404(); function deliver the file like so

resolveResourceOr404 : function (filename, httpRequest, httpResponse) {
    var root = path.join(path.dirname(__filename), '');

    paperboy.deliver(root, httpRequest, httpResponse)
Solution courtesy of: Henrik Andersson


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Correct way to Load JS Files With HTML files through NodeJS


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription