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>
4
  • 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? Commented Nov 12, 2013 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... Commented Nov 12, 2013 at 14:14
  • possible duplicate of how to execute external javascript file in html using node.js Commented Nov 12, 2013 at 14:20
  • See also stackoverflow.com/questions/3225251/… Commented Nov 12, 2013 at 14:33

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.