原生NodeJs制作一个简易聊天室

准备工作

  1. 安装NodeJs环境
  2. 安装编译器Sublime

如果网速不理想,可以百度一下如何加快npm的速度~

使用node搭建一个简单的网站后台

  1. 做完准备工作之后,新建文件夹chatroom,在chatroom中打开cmd,在控制台输出npm init。进行设置,得到package.json文件
{
  "name": "chatroom",
  "version": "1.0.0",
  "description": "multiroom chat server",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "chatroom"
  ],
  "author": "yyg",
  "license": "ISC",
}

  1. 安装socket.io以及mime。执行如下代码:
npm install socket.io --save-dev
npm install mime --save-dev

这里 mime 模块是用于获取所发送文件的类型。使用mime来获取文件类型来设置HTTP头的Content-Type。而 socket.io 则是这个聊天室的主角了,这是一个支持事实通讯而设计的轻量的双向通信协议。

这里推荐一篇文章

3. 在当前文件夹chatroom下新建app.js文件作为整个程序的入口文件,首先引入http,fs,path和mime包。添加如下代码:

var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var socketio = require('socket.io');
  1. 添加访问文件不存在时,返回404页面,在app.js中添加如下代码:
function send404 (res) {
        res.writeHead(404, {'ContentType': 'text/plain'});
        res.write('you are in a black hole');
        res.end();
}

writeHead()第一个参数代表HTTP响应码,404是指没有发现文件。ContentType代表返回文件类型。

  1. 添加提供文件服务,用于给客户端返回相应文件。在app.js中添加如下代码:
function sendFile (res, filePath, fileContent) {
        res.writeHead({
                200,
                'ContentType': mime.lookup(path.basename(filePath))
        });
        res.end(fileContents);
}

200代表返回成功。

  1. 提供静态文件服务。在app.js中添加如下代码:
var cache = {};
function serveStaticFile (res, cache, absPath) {
        if(cache[absPath]) { //检测是否文件已经存在于内存,如果存在直接返回。
                sendFile(res, absPath, cache[absPath]);
        } else {
                fs.exists(absPath, function(exists){ //检测absPath路径下有没有此文件
                        if(exists) {
                                fs.readFile(absPath, function(err, data){
                                        if(err) {
                                                send404(res);
                                        } else {
                                                cache[absPath] = data; //存进内存
                                                sendFile(res, absPath, data);
                                        }
                                });
                        } else {
                                send404(res);
                        }
                });
        }
}
  1. 使用http模块,新建服务器并设置路由。在app.js中添加如下代码:
var server = http.createClient(function(req, res) {
        var filePath = false;

        if(req.url == '/') {
                filePath = 'public/index.html';
        } else {
                filePath = 'public/' + req.url;
        }

        var absPath = './' + filePath;
        serveStaticFile(res, cache, absPath);
});

server.listen(3000, function(req, res) {
        console.log('server started at port 3000');
});

敲完代码,大功告成!接下来再chatroom中新建文件夹public保存静态文件,建立一个主页index,内容随便填写。在命令行中输入node app,在浏览器中打开localhost:3000看看效果吧~

下次再写加入socket.io进行多人聊天