How to include javascript on client side of node.js?

Alxandr is right. I will try to clarify more his answer.

It happens that you have to write a “router” for your requests. Below it is a simple way to get it working. If you look forward www.nodebeginner.org you will find a way of build a proper router.

var fs = require("fs");
var http = require("http");
var url = require("url");

http.createServer(function (request, response) {

    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    response.writeHead(200);

    if(pathname == "https://stackoverflow.com/") {
        html = fs.readFileSync("index.html", "utf8");
        response.write(html);
    } else if (pathname == "/script.js") {
        script = fs.readFileSync("script.js", "utf8");
        response.write(script);
    }


    response.end();
}).listen(8888);

console.log("Listening to server on 8888...");

Leave a Comment