Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。
Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。
1、node模块化:
一切万物皆模块(“简单理解”)
模块化规范: AMD CMD commonjs
nodejs 采用commonjs 的规范
2、模块的分类
1.内置模块:node本身提供的模块不需要下载 直接用
2.自定义模块:根据自己的功能来实现的模块·
3.第三方模块 :npm https://www.npmjs.com
2.1内置模块(看文档)
api可用层次 红色:不能用 黄色:即将不能用 绿色:安全无公害
2.11常用文档(下列文档用法在3内)
1、event
2、fs
3、http
4、url
5、querystring
6、stream
7、path
2.2自定义模块
1.创建一个模块 一个js文件就是一个模块
2.抛出一个模块 module。exports=模块 来进行抛出
3.引入一个模块并且使用 const name=require(’ 文件路径 ')
2.3第三方模块
1.下载
2.引入
3.使用
案例
const http=require('https');
const fs=require('fs');
//发起服务器端的请求
http.get('https://www.baidu.com', (res) => {
// console.log(res)
// console.log(res.statusCode)
const { statusCode } = res;
const contentType = res.headers['content-type'];
console.log(contentType);
let error;//判断状态码和文件格式是否正确
if (statusCode !== 200) {
error = new Error('状态码不是200');
} else if (!/^text\/html/.test(contentType)) {
error = new Error('文件格式不对');
}
if (error) {
console.error(error.message);
// consume response data to free up memory
res.resume();
return;
}
//数据处理
res.setEncoding('utf8');
//设置数据的编码格式
let rawData = '';
res.on('data', (chunk) => {//接受分段数据会触发chunk接受chunk接受到的分数数据
rawData += chunk;
});
res.on('end', () => {
//接受信息完毕 会触发end 方法
fs.writeFileSync('./index.html',rawData);
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
3内置模块方法的介绍
3.1 http:
跨域
创建服务器
爬虫 cheerio 解析标记并提供遍历 each
1.获取网页源代码
2.对源代码进行分析 获取数据
3.2 fs:
文件夹(创建文件夹):
异步fs.mkdir('./haha',(err)=>{
if(err){
console.log("创建错误");
}else{
console.log('ok'); //node的回调函数中有一个规范 错误优先 第一个参数标书是不是错误 null为无错误
}
})
同步
try{
let result=fs.mkdirSync('./haha3');// 同步出错会终止函数执行 需要用try catch捕获错误
}catch(e){
console.log(new Error('错误'))
}
读取文件夹
// fs.readdir('./haha2',(err)=>{
// console.log(err);
// })
删除文件夹
fs.rmdir('./haha2',(err)=>{
console.log(err); //不为空的文件夹不能删除
})
判断文件夹的状态
fs.stat('./haha3',(err,stats)=>{
console.log(err)
console.log(stats)
console.log(stats.isDirectory())
})
文件(在文件操作中所有的路径都需要用绝对路径):
读取文件
1.
// fs.readFile('./haha2/file.txt',(err,data)=>{
// console.log(err);
// console.log(data.toString());
// })
2.
// fs.readFile('./haha2/file.txt','utf8',(err,data)=>{
// console.log(err);
// })
写入文件
// fs.writeFile('./haha2/file.txt','大家好',{flag:'a'},(err,data)=>{
// console.log(err);//如果文件不存在会自动创建 会覆盖原有的文件内容,flag不写默认为w 重写 a为append 追加
// })
写入图片 //通过http请求图片数据然后将图片保存到本地
http.get('图片地址')
res.setEncoding('binary');//数据格式为二进制
fs.writeFile('./a.png',rawData,'binary',(err)=>{
if(err){throw err}
console.log('下载成功');
})
追加文件内容
fs.appendFile('./haha2/xixi.txt','快乐',(err,data)=>{
console.log(err);
})
删除文件
fs.unlink('./haha2/file.txt',(err)=>{
console.log(err)
})
判断文件状态
fs.stat('./haha2/file.txt',(err,stats)=>{
console.log(stats.isFile())
})
案例
// 在一个test文件夹下创建10个文件 文件的名字是 01.txt 02.txt。。。。10.txt
// 每一个文件的内容都是数字 010203
const fs=require('fs');
fs.stat('./test',(err)=>{
if(err){
fs.mkdir('./test',(err)=>{
if(err){throw Error('创建文件夹失败')}
console.log('创建文件夹成功')
for(var i=0;i<10;i++){
fs.writeFile(`./test/${i}.txt`,i,(err)=>{
if(err){throw Error('创建文件失败')}
console.log('创建文件成功')
})
}
})
}else{
console.log('文件已存在');
}
})
3.3 URL 统一资源定位符
https: // user :pass @ sub.host.com : 8080 /p/a/t/h ? query=string #hash
hostname port pathname search
protocol(协议) auth(验证) host(主机) query hsah
path
//分为这几部分
url.parse 格式转换为对象
const url=require('url');
let urlstring='http://www.baidu.com:8080/home/login/test?name=wy&ps=wanger#hash'
const myURL=url.parse(urlstring,false) //false query是字符串格式 true query 是对象格式
console.log(myURL)
ur.format 对象格式转换为url格式
const url=require('url');
let obj={
protocol: 'http:',
slashes: true,
auth: null,
host: 'www.baidu.com:8080',
port: '8080',
hostname: 'www.baidu.com',
hash: '#hash',
search: '?name=wy&ps=wanger',
query: { name: 'wy', ps: 'wanger' },
pathname: '/home/login/test',
path: '/home/login/test?name=wy&ps=wanger',
href: 'http://www.baidu.com:8080/home/login/test?name=wy&ps=wanger#hash'
}
let result=url.format(obj)
console.log(result)
3.4querystring
querystring.escape 编码
const qs=require('querystring'); //主要用于·汉字特殊字符
let code='x=阿瑟&sda=222'
console.log(qs.escape(code));
querystring.unescape 解码
const qs=require('querystring');
let code='x%3D%E9%98%BF%E7%91%9F%26sda%3D222'
console.log(qs.unescape(code))
querystring.parse 将字符串转换为对象
const qs=require('querystring');
let query='us=wangyi&ps=123' //参数二区分键值对 参数三区分键值
console.log(qs.parse(query)); <=====>console.log(qs.parse(query,"&","="));
querystring.stringify将对象转换为字符串
const qs=require('querystring');
let obj={
user:'admin',
pass:123456
}
console.log(qs.stringify(obj,'@',"!"))
3.5path
console.log(_dirname) //获取当前文件所在目录的绝对路径
path.join 作用 :实现路径的拼接 将参数进行智能拼接主要来获取绝对路径
console.log(path.join(_dirname,'./files.js')) <======>console.log(path.join(_dirname,'./','files.js'))
path.basename 获取路径中的文件名
console.log(path.basename('/foo/bar/baz/asdf/quux.html')); quux.html
path.dirname 获取路径中目录名
console.log(path.dirname('/foo/bar/baz/asdf/quux.html')); /foo/bar/baz/asdf/
path.extname 获取路径中文件拓展名
console.log(path.extname('/foo/bar/baz/asdf/quux.html')); .html
path.isAbsolute() 判断路径 绝对路径为true 相对路径为false