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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With