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

I am a full-fledged newbie of node.js and struggling with basics.I have an html file and I would like to invoke an external javascript file on the html page using node.js in the local host environment.

+6
source share
3 answers

Your main file should check if the requested URL is requesting html or js or a 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.

+1
source

You just add a script tag in html:

 <script type="text/javascript" href="/path/to/src.js"></script> 
0
source

I think I understood your real interest.

 <script src="script.js"></script> 

If you are trying to get a script tag (like the one above) working on your html, you should write a β€œrouter” inside your Node.js http.createServer callback. When the browser finds the script tag, it will send a specific request to the server, and then you can send the javascript code back to the response.

I wrote a way to do this on a similar question here: How to enable javascript on the client side of Node.js? .

0
source

Source: https://habr.com/ru/post/957901/


All Articles