TWaver html5 + NodeJS + express + websocket.io + redis 快速搭建项目(三)
在上一篇TWaver html5 + NodeJS + express + websocket.io + redis 快速搭建项目(二)中,给大家介绍了Node.js的安装;本篇将介绍Node.js的使用,您将了解到:
1. Node.js的web框架:express
2. Node.js的实时通讯框架:Socket.IO
3. Node.js的redis客户端:redis
一. express
虽然用Node.js写一个Hello World很简单:
新建一server.js文件,内容如下:
require('http').createServer(function (req, res) {2
res.writeHead(200, {'Content-Type': 'text/plain'});3
res.end('Hello World\n');4
}).listen(8080, "127.0.0.1");然后打开命令行,进入server.js文件所在的目录,运行:node server.js,用浏览器打开http://localhost:8080/即能看到效果:

但稍微复杂的web应用就不能这么原始了,得借助于像express这样的Web Framework了。虽然express提供了Session等功能,还有其他基于express的认证框架passport等,但这里仅仅用express作为静态网页服务:
将如下内容写入server.js文件:
然后在server.js文件所在的目录创建demo目录,并创建demo.html文件,内容如下:
<!DOCTYPE html>2
<html>3
<head>4
<title>Node.js Demo</title>5
</head>6
<body>7
<div>8
Hello Node.js!9
</div>10
</body>11
</html>
前台demo.html修改如下,注意不要漏掉引入Socket.IO js库,而且src地址必须为/socket.io/socket.io.js:
<!DOCTYPE html>2
<html>3
<head>4
<title>Node.js Demo</title>5
<!--引用Socket.IO js库-->6
<script src="/socket.io/socket.io.js"></script>7
<script src="./demo.js"></script>8
</head>9
<body onload="init()">10
<div id="main">11
</div>12
</body>13
</html>
最后重启Node.js,用浏览器重新打开http://localhost:8080/demo.html即能看到效果:

三. redis
redis是Node.js的Redis客户端,封装了Redis的指令,使用很简单,基本和Redis客户端命令一致。这里只用到了hashes,hashes相关的命令参见这里。
开始之前,先切换到seraver.js文件所在的目录,启动redis服务(默认数据将保存在当前目录,文件名为dump.rdb

然后启动redis客户端,运行如下命令,加入测试数据:
hset datas from "{\"id\":\"from\",\"name\":\"From\",\"location\":{\"x\":100,\"y\":100}}"
hset datas to "{\"id\":\"to\",\"name\":\"To\",\"location\":{\"x\":200,\"y\":200}}"
hset datas from-to "{\"id\":\"from-to\",\"name\":\"Hello TWaver HTML5\",\"from\":\"from\",\"to\":\"to\"}"
save
exit

然后,修改后台server.js文件,加载redis模块,并创建redis客户连接:



res.writeHead(
}
浙公网安备 33010602011771号