Node.js learning (70th)

1. Buffer buffer

background

1. The browser does not need to store image files and other media files, and JS stores some basic data types.
2. The server needs to store media files such as pictures/videos/audio, so there is a Buffer buffer.

1. What is Buffer

Buffer is an object similar to an array, the difference is that Buffer is specially used to store binary data.

2. Buffer Features

1. It is an object [similar to an array] used to store data (binary data is stored).
2. The efficiency of Buffer is very high, and the storage and reading are very fast. It directly operates on the memory of the computer.
3. Once the size of the Buffer is determined, it cannot be modified.
4. The size of memory occupied by each element is 1 byte, and its elements are two-digit numbers in hexadecimal. The range of each element is from 00 - ff
5. Buffer is a very core module in Node, no need to download, Can be used directly without importing

3. Buffer operation

3.1 Buffer creation

// 创建一个指定size大小的Buffer
// 安全,里面全是0
var buf = Buffer.alloc(size);  

//不安全,可能包含旧数据,需要重写所有数据
var buf = Buffer.allocUnsafe(size);   

1. Method 1

let buf = new Buffer(10)
console.log(buf)

new Bufferway to create Bufferan instance object of , the performance is particularly poor (you need to open up space in the heap, and then clean up the space - set to zero)

2. Method 2

let buf2 = Buffer.alloc(10)
console.log(buf2)

Create an instance object of Buffer, which has new Buffer()slightly better , and open up a space in the heap (this space has not been used by anyone)

3. Method 3

let buf3 = Buffer.allocUnsafe(10)
console.log(buf3)

Create an Bufferinstance object with the best performance and open up space in the heap.

3.2 Get the length of Buffer

// 获取Buffer的长度
buf.length

3.3 Buffer Conversion

// 相当于Buffer.alloc(size);
var buf = Buffer.allocUnsafe(size);
buf.fill(0)   //将可能出现的敏感数据用0全部填充

// 将一个字符串转换为Buffer
var buf = Buffer.from(str);

// 将一个Buffer转换为字符串
var str = buf.toString();

Notice:

1. Why is the output Buffer not binary?
The output is hexadecimal, but is it stored in binary? It will be automatically converted to hexadecimal when outputting.

2. The output Buffer is not empty?
Opening up space in the heap may leave data used by others, soallocUnsafe

Two, fs file system

1. fs file system in Node

There is a file system in Node. The so-called file system is to add, delete, modify and check files in the computer.
In NodeJs, we provide a module called fs module (file system), which is specially used to operate files.
The fs module is the core module of Node. When using it, it can be imported directly without downloading.

// 引入fs模块
var fs = require("fs");

Most methods in fs provide us with two versions:

1. Synchronous method: the method syncwith
The synchronous method will block the execution of the program.
The synchronous method returns the result through the return value

2. Asynchronous method: the method syncwithout
the asynchronous method will not block the execution of the program.
The asynchronous method returns the result through the callback function

A feature of Nodejs is asynchronous and non-blocking, so all you learn are asynchronous methods.

2. Write fs file

2.1 Ordinary file writing

1. Use synchronously

1. Use fs.openSync()to open the file (this method will return a file descriptor as a result, and various operations can be performed on the file through this descriptor), the parameters are:

1. path: file path
2. flags: type of operation (w, r)

let fd = fs.openSync("./file/test1.txt", "w");

2. Use fs.writeSync()to write the file , the parameters are:

1. fd: file descriptor
2. string: the content to be written
3. position: the starting position of writing (optional)
4. encoding: the coding of writing, the default is utf-8 (optional)

fs.writeSync(fd, "测试文件的第一行文字");

3. Use fs.closeSync()to close the file, the parameters are:

fd: file descriptor

fs.closeSync(fd);

2. Asynchronous use

When using the asynchronous API, you only need to add a callback function on a synchronous basis. The callback function needs to return the corresponding value through parameters. The parameters usually include:

1. err: Error object, if there is no error, it will be null
2. fd: File descriptor

// 打开文件
fs.open("./file/test2.txt", "w", function (err, fd){
    
    
    if(!err){
    
    
        // 写入内容
        fs.write(fd, "异步操作的第一行文字", function (err){
    
    
            if(!err){
    
    
                console.log("成功添加内容");
            }
            // 关闭文件
            fs.close(fd, function (err){
    
    
                console.log(err);
            })
        })
    }
})

2.2 Simple file writing

The simple file writing method is an asynchronous operation. In fact, the following are all asynchronous operations.

1. Use synchronously

Use fs.writeFileSync()to write, the parameters are:

1. path: file path

2. data: the content to be written

3. options: Optional, you can make some settings for writing

fs.writeFileSync("./file/test4.txt", "通过简单文件同步写入的内容");

2. Asynchronous use

Use fs.writeFile()to write, the parameter is one more callback function than synchronization

fs.writeFile(file, data[, options], callback(err) => {
    
    })

1. file: the file path to write + file name + suffix

2. data: the data to be written

3. options: configuration object (optional parameter)

1.encoding:设置文件的编码方式,默认值:utf8(万国码)
2.mode:设置文件的操作权限,默认值是:0o666 = 0o222 + 0o444
    0o111:文件可被执行的权限,.exe .msc 几乎不用,linux有自己一套操作方法。
    0o222:文件可被写入的权限
    0o444:文件可别读取的权限
3.flag:打开文件要执行的操作,默认值是 'w'
   a:追加
   w:写入
4.callback:回调函数
  err:错误对象

Example:

//引入内置的fs模块
let fs = require('fs')

fs.writeFile("./file/test3.txt", "通过简单文件异步写入的内容", function (err){
    
    
    console.log(err);
    if(!err){
    
    
        console.log("写入成功");
    }
})

There is such a principle in Node: error first. So with the callback: err=>{}.

3.flag state

The state of opening the file is as shown in the figure below
insert image description here

2.3 Streaming write

The above two writing methods are not suitable for writing large files, the performance is poor, and it is easy to cause memory overflow, so it is recommended to use the streaming writing method

Streaming file writing can be compared to using a water pipe to transport water from the river to your home. When writing a streaming file, you first need to create a stream (water pipe), and then check the status of the stream. After the file is transferred, you need to close the stream (take open water pipe).

1. Use fs.createWriteStream()to create a writable stream (the water pipe is built), the parameters are:

1. path: file path
2. options: configuration parameters, optional

let ws = fs.createWriteStream("./file/test5.txt");

2. Use ws.write()to enter content into the file:

ws.write("第一次写入");
ws.write("第二次写入");

3. Use ws.close()/ws.end()to close the writable stream (the former will have some errors in the lower version of Node, the water pipe is no longer used, so it has to be put away)

ws.close();
ws.end();

4. Use ws.once()to bind a one-time event to the object to monitor whether the writable stream is closed or not (as long as the stream is used, the state of the stream must be monitored):

ws.once("open", function (){
    
    
    console.log("可写流打开了~~");
})
ws.once("close", function (){
    
    
    console.log("可写流关闭了~~");
})

3. File reading

3.1 Simple reading

Use fs.readFile()to read, the parameter is one more callback function than synchronization

fs.readFile("./file/test1.txt", function (err, data){
    
    
    if(!err){
    
    
        console.log(data.toString());
    }
})

If reading and writing are used at the same time, the effect of copying can be achieved, as follows:

fs.readFile("./file/1.jpg", function (err, data){
    
    
    if(!err){
    
    
        console.log(data);
        fs.writeFile("./file/1_copy.jpg", data, function (err){
    
    
            if (!err){
    
    
                console.log("写入成功~~~");
            }
        })
    }
})

3.2 Streaming read

3.2.1 Regular read+write

To read the data in the readable stream, you need to bind a data event to the readable stream. After the event is bound, it will automatically start reading data (the read data is in the parameters of the callback function)

// 创建一个可读流
let rs = fs.createReadStream("./file/test1.txt");
// 创建一个可写流
let ws = fs.createWriteStream("./file/test1_copy.txt");
// 监听是否开始关闭
rs.once("open", function (){
    
    
    console.log("可读流打开了");
})
rs.once("close", function (){
    
    
    console.log("可读流关闭了");
    ws.end();     //读完了才关,否则读一条就关了
})
// 读取可读流的数据
rs.on("data", function (data){
    
    
    console.log(data);
    // 写入可写流中
    ws.write(data);
})

3.2.2 Easy read + write

There is no need to bind datathe event , just use rs.pipe()the method of the writable stream to directly output the content in the readable stream to the writable stream

// 创建一个可写流
let rs = fs.createReadStream("./file/那些花儿.mp3");
// 创建一个可写流
let ws = fs.createWriteStream("./file/那些花儿_copy.mp3");
// 监听是否开始关闭
rs.once("open", function (){
    
    
    console.log("可读流打开了");
})
rs.once("close", function (){
    
    
    console.log("可读流关闭了");
})
rs.pipe(ws);

4. Other methods

1. fs.existsSync(path): Check whether a file exists
2. fs.stat(path,callback)/fs.statSync(path): Get the status of the file
3. fs.unlink(path,callback)/fs.unlinkSync(path): Delete the file
4. fs.readdir(path[,options],callback)/fs.readdirSync(path[,options]): Read the directory structure of a directory
5. fs.truncate(path,len,callback) / fs.truncateSync(path,len): Truncate the file and modify the file to the specified size
6. fs.mkdir(path,[options],callback) / fs.mkdirSync(path,[options]): Create a directory
7 , fs.rmdir(path,callback) / fs.rmdirSync(path): delete a directory
8, fs.rename(oldPath,newPath,callback) / fs.renameSync(oldPath,newPath): rename the file, and at the same time achieve the effect of moving
9, fs.watchFire(filename[,options],listener): monitor the modification of the file

3. http module

1. Create the most basic web server

1. Import Http module

const http=require('http')

2. Create a web server instance

const server=http.createServer()

3. Bind the request event to the server instance and listen to the client's request

//使用服务器实例的.on()方法,为服务器绑定一个request事件
server.on('request',(req,res)=>{
    
    
//只要有客户端来请求我们自己的服务器,就会触发request事件,从而调用这个事件处理函数
console.log('someone visit our web server.')
})

4. Start the server

//调用server.listen(端口号,cb回调)方法,即可启动web服务器
server.listen(80,()=>{
    
    
console.log('http server running at http://127.0.0.1')
})

2. req request object

As long as the server receives the request from the client, it will call the event processing function server.on()bound to the server. If you want to access data or attributes related to the client in the event processing function, you can use the following methods:request

server.on('request',(req,res)=>{
    
    
//req是请求对象,它包含了与客户端相关的数据和属性,例如:
//req.url是客户端请求的url地址
//req.method 是客户端的method请求类型
const str='Your request url is ${req.url},and request method is ${req.method}'
console.log(str)
}

3. res response object

server.on('request',(req,res)=>{
    
    
//res是响应对象,它包含了与服务器相关的数据和属性,例如:
//要发送到客户端的字符串
const str='Your request url is ${req.url},and request method is ${req.method}'
//res.end()方法的调用:
//向客户端发送指定内容,并结束这次请求的处理过程
res.end(str)
}

4. Solve the problem of Chinese garbled characters

When calling res.end()the method to send Chinese content to the client, there will be garbled characters. At this time, you need to manually set the encoding format of the content

server.on('request',(req,res)=>{
    
    
//发送的内容包含中文
conststr='您请求的url地址是${req.url},请求的method类型是${req.method}'
//为了防止中文显示乱码的问题,需要设置响应头
res.setHeader('Content-Type','text/html;charset=utf-8')
//把包含中文的内容,响应给客户端
res.end(str)
})

5. Respond to different html content according to different urls

server.on('request',function(req,res){
    
    
const url =req.url //1.获取请求的Url地址
let content ='<h1>404 Not found!</h1>'//2.设置默认的内容
if(url=='/'||url ==='/index.html'){
    
    
content='<h1>首页</h1>'//3.用户请求的是首页
}else if(url==='/about.html'){
    
    
content='<h1>关于页面</h1>'
}
//为了防止中文显示乱码的问题,需要设置响应头
res.setHeader('Content-Type','text/html;charset=utf-8')
//把包含中文的内容,响应给客户端
res.end(str)
})

Guess you like

Origin blog.csdn.net/weixin_55608297/article/details/128227467