I am a complete node.js newbie and struggling with the basics.I have a html file and I would like to call external javascript file in the html page using node.js in local host environment.
Your main file should check whether the requested url is asking for html or js or css file.
var server = http.createServer(function(request, response) {
console.log("Received Request: " + request.url);
if(request.url.indexOf('.html') != -1) {
fs.readFile("game" + request.url, function (error, data) {
if (error) {
response.writeHead(404, {"COntent-type":"text/plain"});
response.end("No Html Page Found.");
} else{
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
}
});
}
else if(request.url.indexOf('.js') != -1) {
fs.readFile("game" + request.url, function (error, data) {
if (error) {
response.writeHead(404, {"COntent-type":"text/plain"});
response.end("No Javascript Page Found.");
} else{
response.writeHead(200, {'Content-Type': 'text/javascript'});
response.write(data);
response.end();
}
});
}
else if(request.url.indexOf('.css') != -1) {
fs.readFile("game" + request.url, function (error, data) {
if (error) {
response.writeHead(404, {"COntent-type":"text/plain"});
response.end("No Css Page Found.");
} else{
response.writeHead(200, {'Content-Type': 'text/css'});
response.write(data);
response.end();
}
});
}
else {
console.log("Inside the inside else statement");
response.writeHead(404, {"COntent-type":"text/plain"});
response.end("No Page Found");
}
});
After That you can include external javascript and css files in html files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With