Home  >  Article  >  Web Front-end  >  A novice’s approach to building a web server using nodejs

A novice’s approach to building a web server using nodejs

不言
不言Original
2018-09-14 17:22:291805browse

The content of this article is about the beginner’s method of building a web server with nodejs. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

nodejs builds a simple web server

1.1 Introduction

Node.js is a platform based on the Chrome JavaScript runtime. In fact, it is an adaptation of Google Chrome The V8 engine is encapsulated and is primarily used to create fast, scalable network applications.

In other words, the browser's Javascript is the browser's js code parser, while Node.js is the server-side JS code parser. The JS code stored on the server side is parsed and applied by Node.js.

Note: Although Nodejs and js are the same product in a sense, the writing and usage are different, but the point is, nodejs is on the scope server side, js is only on the scope browser side, js It can point to the browser, but nodejs cannot point to the browser, so some APIs are different.

Similarly: js is a weakly typed language, so nodejs is also a weakly typed language. There will be deviations in the language algorithm. If you develop a banking system or payment system, do not use nodejs. (nodejs is suitable for IO-intensive applications, not CPU-intensive applications.)

1.2node module type

Module types include:   

1)Officially provided native module
global, util, querystring, url, buffer, fs, http,
2) Third-party module
mysql, oracle, express
3) Custom module
File module and directory module

1.3 Commonly used native modules - key points of difficulty

1) The querystring module is used to process the query string in the http request url
var obj=qs.parse(str); Put the query Parse the string into a js object
var str=qs.parse(obj); Convert the js object into a query string

2) The url module is used to parse an http request address and obtain each different Part
var obj = url.parse(str) Parses a url string into an object
var obj = url.parse(str,true) Parses a url string into an object and converts the The query string is also parsed into an object

3) buffer The buffer is essentially a memory area used to temporarily store data to be used in the future (may be numbers, strings, binary pictures, audio and video, etc.) ,
This area becomes the "cache". ******Global objects do not require require references******

//创建一个大小为10字节的缓冲区
var buf1 = Buffer.alloc(10); //alloc:分配
console.log(buf1);
var buf2 = Buffer.alloc(1024*3); //alloc:分配3kb大小的缓冲区
console.log(buf2);
var buf3=Buffer.from(['a','b','c']);
console.log(buf3);
//使用一个字符串创建一个缓冲区
var buf4=Buffer.from('abcd');
console.log(buf4);
var buf5=Buffer.from('一二三文');
console.log(buf5);
//把缓冲区的内容转换为字符串
console.log(buf5.toString());

4) fs file system module
The fs module provides the functions of adding, deleting, modifying, checking, reading and writing files/directories in the file system.

//同步读取文件中的内容
var data=fs.readFileSync(file);
//同步向文件中写出内容(删除已有内容)
fs.writeFileSync(file,str/buf);
//同步向文件中追加写出内容(不删除已有内容)
fs.appendFileSync(file,str.buf)
例如fs异步读写文件 不需要等待直接往下走
//异步读取文件中的内容
fs.readFile(file,funcgtion(err,data){
});
//异步向文件中写出内容(删除已有内容)
fs.writeFile(file,str/buf,function(){
});
//异步向文件中追加写出内容(不删除已有内容)
fs.appendFile(file,str.buf,function(){

});

5) The http module can be used to write client programs (i.e. browsers) based on the http protocol;
can also be used to write servers based on the http protocol End program (i.e. web server)
Use http module to write web server: var server=http.createServer();
1) Receive the client’s http request message
2) Parse the client request message
3) Read the file requested by the client.
4) Send an http response message to the client, the main body is the file requested by the client

1.4 How to build a web server

Having talked about the above, we can talk about how to Build a small web server with nodejs! (Look carefully at the code and comments below!)

const http=require('http'); 
const url=require('url');
const fs=require('fs'); //引用模块前面讲过啦每个模块都是干嘛的
//创建一个http服务器
var server=http.createServer();
//让http服务器监听指定的端口
server.listen(80);
//当客户端请求到来时,处理请求消息
server.on('request',function(req,res){
    //处理消息 req请求消息,res响应消息
    console.log('nodejs服务器接收到一个请求');
    //解析客户端发来的请求消息
    console.log('请求地址'+req.url);
    var objURL=url.parse(req.url);
    /*console.log(objURL);*/
    res.setHeader('Content-Type','text/html;charset=utf-8');
    var path = objURL.pathname;
    if(path==='/login'){
        
        /*res.write(&#39;<h1>欢迎访问登录页面</h1>&#39;);*/
        fs.readFile(&#39;./public/login.html&#39;,(err,data)=>{  
            if(err){
                res.write(&#39;<h1>报错了</h1>&#39;);
            }else{
                res.statusCode=200;
                res.write(data);
                res.end();
            }
        });
        
    }else if(path===&#39;/index&#39;){
        
        fs.readFile(&#39;./public/index.html&#39;,(err,data)=>{
            if(err)throw err;//若存在错误抛出错误,后面不执行
            res.statusCode=200;
            res.write(data);
            res.end();
            
        });
    }else{
        
        fs.readFile(&#39;./public/404.html&#39;,(err,data)=>{
            if(err){
                res.write(&#39;<h1>报错了</h1>&#39;);
            }else{
                res.statusCode=404;
                res.write(data);
                res.end();
            }
        });
    }
});

This article is suitable for beginners. If you want to build a sound web server, you need more knowledge about middleware.

The above is the detailed content of A novice’s approach to building a web server using nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn