6

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>
Dan Kanze
  • 18,485
  • 28
  • 81
  • 134
Pradeep Raj
  • 339
  • 2
  • 5
  • 12
  • 1
    Just put it in `script` tags in your HTML file that you're serving up. You want to use this JS on the client side right? – tymeJV Nov 12 '13 at 14:07
  • 1
    The server and client are separated. An HTML file can only use Client-side JS scripts, and the Server can only reference server side JS scripts... – egucciar Nov 12 '13 at 14:14
  • possible duplicate of [how to execute external javascript file in html using node.js](http://stackoverflow.com/questions/19926787/how-to-execute-external-javascript-file-in-html-using-node-js) – Paul Mougel Nov 12 '13 at 14:20
  • See also http://stackoverflow.com/questions/3225251/how-can-i-share-code-between-node-js-and-the-browser – Plato Nov 12 '13 at 14:33

1 Answers1

2

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

Hector Correa
  • 26,290
  • 8
  • 57
  • 73