One, handle I/O
1. Asynchronous non-blocking I/O
Regarding the above concepts, there is a very classic explanation of the kettle on the Internet
Uncle Wang next door has a kettle, and Uncle Wang often uses it to boil water.
(Synchronous blocking): Uncle Wang puts the kettle on the fire, then does nothing, just wait there, until the water boils, Uncle Wang will do other things.
(Synchronous non-blocking): Uncle Wang thought he was a bit naive and didn't plan to wait anymore. After putting the kettle on, he went to the show, and took a look at the water from time to time.
(Asynchronous blocking): Uncle Wang went to buy a ringing kettle, he put the kettle on the fire, and then waited for the water to boil. The kettle would make a sound when the water was boiling.
(Asynchronous non-blocking): Uncle Wang feels a bit silly. He puts the kettle on the fire and goes to the show. He doesn't have to look at it from time to time, because the kettle will make a sound to inform the uncle when the water is boiling.
//03-fs.js
const fs=require('fs');
//同步调用
const data=fs.readFileSync('./conf.js');//代码会阻塞在这里
console.log(data);
//异步调用
fs.readFile('./conf.js',(err,data)=>{
if(err) throw err;
console.log(data);
})
//promisify
const{
promisify}=require('util')
constreadFile=promisify(fs.readFile)
readFile('./conf.js').then(data=>console.log(data))
//fs Promises API node v10
const fsp=require("fs").promises;
fsp
.readFile("./confs.js")
.then(data=>console.log(data))
.catch(err=>console.log(err));
//async/await
(async()=>{
const fs=require('fs')
const{
promisify}=require('util')
const readFile=promisify(fs.readFile)
const data=await readFile('./index.html')
console.log('data',data)
})()
//引用方式
Buffer.from(data).toString('utf-8')
Two, Buffer buffer
The read data type is Buffer
Buffer-Used to interact with octets in TCP streams, file system operations, and other contexts. Data composed of octets can effectively store binary data in Js.
//04-buffer.js
//创建一个长度为10字节以0填充的Buffer
const buf1=Buffer.alloc(10);
console.log(buf1);
//创建一个Buffer包含ascii.
//ascii查询http://ascii.911cha.com/
const buf2=Buffer.from('a')
console.log(buf2,buf2.toString())
//创建Buffer包含UTF-8字节
//UFT-8:一种变长的编码方案,使用1~6个字节来存储;
//UFT-32:一种固定长度的编码方案,不管字符编号大小,始终使用4个字节来存储;
//UTF-16:介于UTF-8和UTF-32之间,使用2个或者4个字节来存储,长度既固定又可变。
const buf3=Buffer.from('Buffer创建方法');
console.log(buf3);
//写入Buffer数据
buf1.write('hello');
console.log(buf1);
//读取Buffer数据
console.log(buf3.toString());
//合并Buffer
const buf4=Buffer.concat([buf1,buf3]);
console.log(buf4.toString());
//可以尝试修改fs案例输出文件原始内容
Buffer is similar to an array, so many array methods have GBK transcoding iconv-lite
Three, HTTP service
Create an HTTP server, 05-http.js
http=require('http');
const server=http.createServer((request,response)=>{
console.log('thereisarequest');
response.end('aresponsefromserver');
});
server.listen(3000);
//打印原型链
functiongetPrototypeChain(obj){
varprotoChain=[];
while(obj=Object.getPrototypeOf(obj)){
//返回给定对象的原型。如果没有继承属性,则返回null。
protoChain.push(obj);
}
protoChain.push(null);
return protoChain;
}
Show a homepage
const{
url,method}=request;
if(url==='/'&&method==='GET'){
fs.readFile('index.html',(err,data)=>{
if(err){
response.writeHead(500,{
'Content-Type':'text/plain;charset=utf-8'});
response.end('500,服务器错误');
return;
}
response.statusCode=200;
response.setHeader('Content-Type','text/html');
response.end(data);
});
}else{
response.statusCode=404;
response.setHeader('Content-Type','text/plain;charset=utf-8');
response.end('404,页面没有找到');
}
Write an interface
elseif(url==='/users'&&method==='GET'){
response.writeHead(200,{
'Content-Type':'application/json'});
response.end(JSON.stringify([{
name:'tom',age:20}]));
}
Four, stream
stream-is the interface used to interact with the data stream in node
//二进制友好,图片操作,06-stream.js
const fs=require('fs')
const rs2=fs.createReadStream('./01.jpg')
const ws2=fs.createWriteStream('./02.jpg')
rs2.pipe(ws2);
//响应图片请求,05-http.js
const{
url,method,headers}=request;
elseif(method==='GET'&&headers.accept.indexOf('image/*')!==-1){
fs.createReadStream('.'+url).pipe(response);
}
Accept represents the type of data that the sender (client) wants to accept. For example: Accept: text/xml; represents that the data type that the client wants to accept is the xml type.
Content-Type represents the data type of the entity data sent by the sender (client | server). For example: Content-Type: text/html; represents that the data format sent by the sender is html.
Together, Accept: text/xml; Content-Type: text/html, which means that the data type you want to accept is xml format, and the data format of the data sent in this request is html.