Correct way to Load JS Files With HTML files through NodeJS

sia picture sia · Nov 12, 2012 · Viewed 13.3k times · Source

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 socket.io 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"});  
        response.write(html);  
        response.end();  
    }).listen(port.number);
});

Default.html Page

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="objects/css/site.css" type="text/css" />
    <script src="objects/js/jquery.min.js" type="text/javascript"></script>
    <script src="objects/js/site.min.js" type="text/javascript"></script>
</head>

<body></body>    

</html>

Answer

Daniel picture Daniel · Nov 12, 2012

Your Javascript and styles are failing because they don't exist. Your current webserver is only sending a single route, the root route. Instead you'll need to allow the use of multiple routes. ExpressJS does this for you in a simpler way, but still very possible without it.

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


    var server = http.createServer(function(request, response){
       var header_type = "";
       var data        = "";
       var get = function (uri, callback) {
           // match `request.url` with uri with a regex or something.
           var regex = uri;
           if (request.url.match(regex)) {
               callback();
           }
       };    

       var render = function (resource) {
           // resource = name of resource (i.e. index, site.min, jquery.min)
           fs.readFile( __dirname + "/" + resource, function(err, file) {
              if (err) return false; // Do something with the error....
              header_type = ""; // Do some checking to find out what header type you must send.
              data = file;
           }
       };

       get('/', function(req, res, next) {
           // Send out the index.html
           render('index.html');
           next();
       });


       get('/javascript.min', function(req, res, next) {
          render('javascript.js');
          next();
       });


    });

    server.listen(8080);

This might get you started, but you'll have to implement some things like next() yourself. A pretty simple solution, but a working one.

Another solution for responding to static files would be to create a catcher within the http.createServer callback. Within the get method, if the uris don't match, then you would look within a public folder matching the full uri to the file system structure.