Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call external javascript file in html using 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.

JS:

var http = require('http'),
fs = require('fs');
fs.readFile('HtmlPage.html', function (err, html) {
  if (err) {
    throw err; 
  }
});       
http.createServer(function(request, response) {  
    response.writeHeader(200, {"Content-Type": "text/html"});  
    response.write(html);  
    response.end();  
}).listen(8000);});

HTML:

<script type="text/javascript" >
function validation() {
  alert("Hai");            
  var fs = require("JavaScript1.js");
}
</script>
like image 892
Pradeep Raj Avatar asked Nov 01 '22 10:11

Pradeep Raj


1 Answers

Keep in mind that the JavaScript that you have in the HTML page will run on the browser, not on the server.

Therefore your alert("Hai"); will execute just fine since that's typical client-side javascript code, but server-side code like var fs = require("JavaScript1.js"); will not.

There are ways to share client and server side javascript code as others pointed out in the comments, but I suspect that's not what you are after given that you are starting to learn Node.js

The fact that you are using Node.js in the server does not give you new JavaScript powers on the client side automatically. As far as the browser is concerned the server could be Ruby or C#.

Also, I would write your server-side code like this:

var http = require('http'),
var fs = require('fs');
http.createServer(function(request, response) {  

   fs.readFile('HtmlPage.html', function (err, html) {
     if (err) {
        throw err; 
     }

    response.writeHeader(200, {"Content-Type": "text/html"});  
    response.write(html);  
    response.end();  

   });       

}).listen(8000);});

I've got an Intro to Node.js blog post that might help you in the beginning: http://hectorcorrea.com/blog/introduction-to-node-js

like image 75
Hector Correa Avatar answered Nov 14 '22 07:11

Hector Correa