Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...