1

I have read many questions regarding "unable to load js and css files from node js". Looks like a silly path error but since am new to node js, am unable to figure it out. All of my files are under one folder named "d3". Any ideas where am going wrong?

var http = require('http');
var fs = require('fs');
var url = require('url');
var io = require('socket.io');
var redis = require('redis');
var redis = require("redis")
, subscriber = redis.createClient();

subscriber.subscribe('channel');
var server = http.createServer(function(request, response){
    var path = url.parse(request.url).pathname; 
    switch(path) {
        case '/socket.html':
        fs.readFile(__dirname + path, function(error, data){
            if (error){
                console.log("Working " + error);                        
                response.writeHead(404);
                response.write("File doesn't exist - 404");
                response.end();
            }
            else{
                response.writeHead(200, {"Content-Type": "text/html"});
                response.write(data, "utf8");
                response.end();
            }
        });
        break;

        default:
        response.writeHead(404);
        response.write("Doesnt Exist");
        response.end();
        break;
    }
});

/* Rest of the code */

server.listen(8000);
0

1 Answer 1

2

When node JS gets a request, you pass the requested path into a switch statement.

If the request is for /socket.html you return an HTML document.

If the request if for anything else (such as my.js), you return a 404 error.

You have to return the JS and CSS when it is requested instead of throwing a 404.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks mate. Didnt have any idea that it will take the paths from here.
Hey! I hope you have a look at this issue am facing stackoverflow.com/q/37125138/2976463

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.