How to include nodejs modules in html files?


Question

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.

1
11
9/9/2012 4:06:28 PM

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).

14
4/15/2012 9:46:19 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon