内置模块【Node.js自带的模块】
直接引用内置模块: const/var/let 变量名 = require( 模块名 )
内置模块详解
Url:
parse:将地址路径转换成对象
const url = require('url');
console.log(url.parse('https: //nodejs.org/dist/latest-v10.x/docs/api/url.html#url_class_url'))
format:是将传入的url对象编程一个url字符串并返回
const url = require('url');
console.log(url.format({
protocol: 'https',
hostname: 'example.com',
pathname: '/some/path',
query: {
page: 1,
format: 'json'
}
}));
终端运行结果:
https://example.com/some/path?page=1&format=json
Querystring:
是做字符串格式化
parse:将字符串转为对象
const querystring = require('querystring');
let str = 'https://www.baidu.com/s?ie=UTF-8&wd=npm官网';
console.log(querystring.parse(str));
终端运行结果:
{ 'https://www.baidu.com/s?ie': 'UTF-8', wd: 'npm官网' }
stringfly:将对象转为字符串 【 编码 】
console.log(querystring.stringify({ 'https://www.baidu.com/s?ie': 'UTF-8', wd: 'npm官网' }))
终端运行结果:
https%3A%2F%2Fwww.baidu.com%2Fs%3Fie=UTF-8&wd=npm%E5%AE%98%E7%BD%91
escape:将中文进行编码
let nameStr = 'name=张三';
console.log(querystring.escape(nameStr))
终端运行结果:
name%3D%E5%BC%A0%E4%B8%89
unescape:将中文进行解码
console.log(querystring.unescape('https: //www.baidu.com/s?ie=UTF-8&wd=npm%E5%AE%98%E7%BD%91'))
终端运行结果:
https: //www.baidu.com/s?ie=UTF-8&wd=npm官网
Http
get:请求接口数据
http.get('接口路径',callback)
const http = require('http') //引入http模块
//直接查看http的api
http.get('http://api.k780.com/?app=weather.city&cou=1&appkey=43880&sign=6a31f4fe1408d69bb0417b046eeae5b6&format=json', (res) => {
const { statusCode } = res; //获取请求的状态码
const contentType = res.headers['content-type']; //获取请求的数据类型
// json数据的content-type 'content-type': 'application/json'
let error;
if (statusCode !== 200) { //如果状态码不是200,输出错误信息
error = new Error('请求失败\n' +
`状态码: ${statusCode}`); //输出错误和状态码
} else if (!/^application\/json/.test(contentType)) { //检测json的contentType
error = new Error('无效的 content-type.\n' +
`期望的是 application/json 但接收到的是 ${contentType}`);
}
if (error) { //如果存在错误
console.error(error.message);
// 消费响应数据来释放内存。
res.resume();
return; //终止代码执行
}
res.setEncoding('utf8'); //编码
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; }); //通过data事件拼接数据流
res.on('end', () => { //获取数据结束
try { //捕获错误信息
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`出现错误: ${e.message}`);
});
http.createServer:创建服务器
const http = require('http'); //引入http模块
const host = 'localhost'; //主机名
const port = 1000; //端口号,自己随意设置
http.createServer((request, response) => {
// response.writeHead(状态码, 请求头),状态码设为200,表示请求成功,设置请求头主要是为了设置字符编码,否则会乱码
response.writeHead(200, {
'content-type': 'text/html;charset=utf8'
})
response.write('<i>Hello,World!</i><br><b>你好,世界!</b>')
response.end(); //告诉前端信息发送已结束
}).listen(port, host, () => {
console.log(`The server is running at:http://${host}:${port}`)
})
- cheerio
爬虫
* 去某一个网站爬取一段数据 -> 数据清洗 -> 后端服务器 -> 发送前端 -> 渲染数据
* 不是所有网站都可以爬取
* 反爬虫 :
* 爬虫: 后端渲染的网站
【注意】
后端服务器有两种类型
1. web服务器 【 静态服务器 】
2. api服务器 【 暴露接口 】
请求头部报文
1. general 请求基本信息
2. response Headers 响应头
3. request Headers 请求头
4. 携带参数
- query string paramters get请求
- form data post 请求
Events:事件触发器
Node.js中 事件的发布 + 事件的订阅 表示一个任务的执行
const EventEmitter = require('events'); //引入事件模块
const fs = require('fs'); //引入文件系统模块
const http = require('http');
const host = 'localhost';
const port = 2000;
class MyEmitter extends EventEmitter {} //类的继承
const myEmitter = new MyEmitter(); //实例化
//事件发布
myEmitter.on('event', () => {
//书写任务
http.createServer((request, response) => {
response.writeHead(200, {
'content-type': 'text/html;charset=utf8'
})
//fs.readFile('文件路径',[options],(error,data)=>{})
//[options]可省略,如果为字符串,则它制定字符编码,回调函数中的data指的是文件内容
fs.readFile('./test.txt', 'utf8', (error, docs) => {
response.write(`<h3>${docs}</h3>`);
response.end()
})
}).listen(port, host, () => {
console.log(`The server is running at http://${host}:${port}`)
})
});
//事件订阅
myEmitter.emit('event');
Stream(流):是 Node.js 中处理流式数据的抽象接口。
流指的是数据流,指的是数据是分片传输
数据可以实现非阻塞
gulp 【 流式操作 】
案例: 打包压缩包
流程:
- 读取文件
- 创建压缩包
- 将读取的数据流写入压缩包
- 输出压缩包
const fs = require(‘fs’); //引入fs文件系统模块
const zlib = require(‘zlib’); //引入创建压缩包的模块
const inp = fs.createReadStream(’./test.txt’) //读取需要压缩的文件内的数据
const gzip = zlib.createGzip(); //创建压缩包
const outp = fs.createWriteStream(’./test.txt.gz’) //
inp.pipe(gzip).pipe(outp)//输出压缩包
第三方模块【别人创建好的模块】
直接看api粘贴调用
request:用来请求数据
const request = require('request')
request('https://m.lagou.com/listmore.json', function(error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
终端运行结果是数据接口的所有数据
自定义模块【自己创建的模块】
- 创建模块
- -对象、数组、字符串、函数······
const Class = {
num: 100,
teacher: 'yan',
day: 60,
}
- 导出模块(两种方式)
module.exports = {
Class
}//此处可以批量导出,因为是对象,可以放多个,
// module.exports = Class 此种方法导出模块安全性不好,只能导出一个
- 引入模块并使用
const { Class } = require('./2-selfdefine') //此处必须为相对路径
// const Class = require('./2-selfdefine')
console.log(Class.teacher)//yan