Native Nodejs to write online chat system

Source: Internet
Author: User

Front-end automation has been a long-standing, recently in order to write their own automation tools, I began to study node in detail, in order to test the results of learning, decided to write a chat system similar to WEBQQ. The following are the modules that the system has.

  • Login module (Automatic login)
  • Chat module (private chat, group chat)
  • Statistical module (degree of activity over time)
  • Geography module (Find nearby)

This article mainly describes how to write a static resource server with node. js.

Pre-preparation

Now that you're writing with node. JS, the first thing to do is download and install the latest version of node.

Start the service

Nodejs the way to start a server is simply to call the native module (HTTP) of node and call its Createserver method.

const http = require(‘http‘);const Until = require(‘./app/core/router‘);global.BASE_DIR = __dirname;global.VIEW = global.BASE_DIR + ‘/view/‘;http.createServer((req, res) => { // 第一个参数为请求第二个参数为回应    "use strict";    Until.init(req.url, req).then(reslove => {        if (!reslove) {            return        }        res.writeHead(200, {‘Content-Type‘: reslove.type +‘; charset=utf-8‘}); // charset=utf-8 指定编码方式        res.end(reslove.response)    })}).listen(3000) 端口号
Routing

When the service is started, we will start to write the entire system routing, all system requests are divided into three categories: one is to request the front page, the second is to request static resources, and three is to request data. We need some tags to identify the request for proper handling.

    getRes(url) {        "use strict";        url = url.toString();        if (url.includes(‘.html‘) || (!url.includes(‘.‘) && !url.includes(‘/api/‘))) { // 页面            return this.renderHtml();        } else if (url.includes(‘/api/‘)) { // api            return this.renderApi();        } else if (url.includes(‘.‘)){            return this.renderRrsource(); // 静态资源        }    },

The following is an example of a login page that describes the request and response process. We assume that '/login ' is the link to the login page, when the server receives the request, two things need to be done, one is to find the login page, and the second is to return the page to the foreground.

    The file renderfile (filename, num) {"Use strict") is returned if the file exists. Let Path_arr = [Global. VIEW + filename + '. Jade ', Global.            Base_dir + filename] return new Promise ((Reslove, reject) = {Let path = Path_arr[num], type;                Fs.access (Path, (err) = {//detects if the file exists if (err) {reject (err); } else {if (num = = 0) {//returns page Reslove ({type: ' text/html ', Response:jade.ren                             Derfile (Path)})} else {//return static resource Fs.readfile (path, (err, data) = {                                if (err) {Reject (err)} else {                                if (Path.includes ('. css ')) {type = ' text/css ')                 } else if (Path.includes ('. js ')) {type = ' application/x-javascript '               } reslove ({type:type, response:data})} })                    }                }            })        })    },

Above is the logic to request resources and files, similar interfaces. Finish the effect:

Native Nodejs to write online chat system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.