Reputation: 87
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);
Upvotes: 1
Views: 382
Reputation: 943569
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.
Upvotes: 2