Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include nodejs modules in html files?

First of all I am new to nodejs and secondly below is my question. How to include nodejs net module in js which is loaded in html??

My js file looks like this.

net = require('net');
var client = net.createConnection(8000, '192.168.15.59');
client.on('connect',function(){
console.log('Connected To Server');
});
client.on('data',function(data){
console.log('Incoming data:; ' + data);
});

And my html file is below

<html>
<head>
<script type="text/javascript" src="sample.js"></script>
<script type="text/javascript">
function displaymessage(message)
{
alert(message);
client.write(message, encoding='utf8')
}
</script>
</head>

<body>
<form>
<input type="text" id="msg"></input>
<input type="button" value="Click me!" onclick="displaymessage(document.getElementById('msg').value)" />
</form>
</body>
</html>

When I run the HTML file in browser it gives below error

Uncaught ReferenceError: require is not defined

whereas if I run the js file directly in nodejs (like this "node sample.js) using command line then it works fine.

Thanks in advance.

like image 358
Farooq Arshed Avatar asked Apr 15 '12 21:04

Farooq Arshed


People also ask

How do I link a NodeJS file in HTML?

For html page we have to use URL so for that in Node JS “url” module has been used so we have to add this module in our program file. And then we can get the path of request URL as shown below. var url=require("url"); var path=url.

How do I add a module to a script tag?

Simply add type="module" to your script tags and the browser will load them as ES Modules.


2 Answers

NodeJS runs on the server. Script inside HTML files runs on the client. You don't include server code on the client. Instead, you send messages to the server code from the client, and interpret the results. So the standard way to do this is to define a resource on the server that generates the content or data you want to generate, and to retrieve that content or data from the client, using just normal page loading or "ajax" (although these days, most people don't use the "x" [XML] in "ajax" [some still do], they use JSON, text, or HTML).

like image 196
T.J. Crowder Avatar answered Oct 07 '22 21:10

T.J. Crowder


To clarify what @T.J.Crowder said in the comment: What you are trying to do is impossible.

NodeJS is a server-side framework. The Javascript you write in NodeJS is executed on the server. The Javascript you write for your HTML pages is executed on the client. The client and server can not call each other's methods directly. This is what AJAX and other asynchronous client-server communication techniques are used for.

like image 34
Travis Webb Avatar answered Oct 07 '22 21:10

Travis Webb