如何在 html 文件中包含 nodejs 模块? [英] How to include nodejs modules in html files?

查看:349
本文介绍了如何在 html 文件中包含 nodejs 模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我是 nodejs 的新手,其次下面是我的问题.如何在 html 中加载的 js 中包含 nodejs 网络模块??

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??

我的 js 文件是这样的.

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);
});

我的 html 文件在下面

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>

当我在浏览器中运行 HTML 文件时,它给出以下错误

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

未捕获的 ReferenceError: require 未定义

Uncaught ReferenceError: require is not defined

而如果我使用命令行直接在 nodejs 中运行 js 文件(如node sample.js"),则它可以正常工作.

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

提前致谢.

推荐答案

NodeJS 在服务器上运行.HTML 文件中的脚本在客户端上运行.您不在客户端包含服务器代码.相反,您从客户端向服务器代码发送消息,并解释结果.因此,执行此操作的标准方法是在服务器上定义一个资源来生成您想要生成的内容或数据,并从客户端检索该内容或数据,仅使用正常的页面加载或ajax"(尽管现在大多数人不使用 "ajax" 中的 "x" [XML]" [有些仍然这样做],他们使用 JSON、文本或 HTML.

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

这篇关于如何在 html 文件中包含 nodejs 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆