Node.js
1. 流
- 入:可写的流
- 出:可读的流
- data:Node.js中数据是分片【 chunk 】传输的
- 为了提高性能,减少能耗【 cpu 】
- 管道流 【 连接 I/O 之间的一个管道】,这个管道我们称之为: pipe
- gulp就是引来了Node.js流的概念,它才能在grunt竞争中胜出
const zlib = require('zlib')
const fs = require('fs')
const inp = fs.createReadStream('./dist/1.txt')
const out = fs.createWriteStream('1.txt.gz')
const gzlib = zlib.createGzip()
inp
.pipe(gzlib)
.pipe(out)
2. 爬虫
- 通过后端语言爬取网站中的数据,然后通过特定模块进行数据清洗,最后将数据输出给前端
- 不是那个网站都能爬取的
- 作业: 拉钩网首页列表
const http = require('https')
const options = {
hostname: 'www.lagou.com',
port: 443,
method: 'GET',
header: {
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Cache-Control': 'max-age=0',
Connection: 'keep-alive',
Cookie: 'user_trace_token=20190813113601-2bc1b60b-b8d3-4b1f-98e0-96f6ecd2ee21; _ga=GA1.2.96844005.1565667362; LGUID=20190813113601-78eda565-bd7b-11e9-a500-5254005c3644; JSESSIONID=ABAAABAAAFCAAEG0897031F7BB1FA006CA69C5E8F7D9B4B; WEBTJ-ID=20190813113606-16c890c183b2d6-0cdfdcf9f1128-36664c08-2073600-16c890c183c148; _gid=GA1.2.40821466.1565667367; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1565667367,1565667417,1565667518,1565668611; X_MIDDLE_TOKEN=055f0fccb529b49807879d13d98f4034; index_location_city=%E6%9D%AD%E5%B7%9E; LGSID=20190813164735-ff5802d3-bda6-11e9-a500-5254005c3644; TG-TRACK-CODE=index_search; SEARCH_ID=3e0f3a2340064ae7bedac0082352b57c; X_HTTP_TOKEN=3a3838c4d689888e00078656518a2899a29646e597; LGRID=20190813170320-3253f1e6-bda9-11e9-8993-525400f775ce; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1565687000',
Host: 'www.lagou.com',
'Upgrade-Insecure-Requests': 1,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 0
}
};
http.get(options, (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type']; // 文件类型 text/json/html/xml
res.setEncoding('utf8'); // 字符编码
// 核心 -- start
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; }); // 数据拼接
res.on('end', () => { // 数据获取结束
try {
console.log(rawData);
} catch (e) {
console.error(e.message);
}
});
// 核心 -- end
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
3. 服务器
- 后端中服务器类型有两种
- web服务器【 静态服务器 】
- 举例: wamp里面www目录
- 目的是为了展示页面内容
- 前端: nginx
- 应用级服务器[ api服务器 ]
- 做什么?
- 使用Node.js原生代码实现静态服务器 【 必会 】
const http = require( 'http' )
const port = 3000
const hostname = 'localhost'
http.createServer((request,response) => {
response.writeHead( 200, {
'Content-Type': 'text/html;charset=utf8'
})
response.write('hello Node.js - 千锋教育')
response.end()
}).listen(port,hostname,() => {
console.log(`The Server is running at: http://${ hostname }:${ port }`)
})