Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to execute external javascript file in html using node.js

Tags:

node.js

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.

like image 671
Pradeep Raj Avatar asked Nov 12 '13 10:11

Pradeep Raj


1 Answers

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.

like image 108
Anish Tangbe Avatar answered Oct 10 '22 02:10

Anish Tangbe