第⼆章 NodeJs核⼼模块api-基础
第1集 Buffer缓冲器常⽤api (⼀)
简介:介绍buffer缓冲器类常⽤的api使⽤
buffer⽤于处理⼆进制数据,在v8堆外分配物理内存,buffer实例类似0-255之间的整数数组,显 示的数据为⼗六进制,⼤⼩是固定的,⽆法修改。
创建buffer
Buffer.alloc(size[, fill[, encoding]]):
Buffer.allocUnsafe(size):
Buffer.from(array):
Buffer.from(string[, encoding]):
// 1、Buffer.alloc(size)
console.log(Buffer.alloc(10));
// 2、Buffer.allocUnsafe(size) 可能会存在脏数据
console.log(Buffer.allocUnsafe(10));
// 3、Buffer.from(array)
console.log(Buffer.from([1, 2, 3]));
// 4、Buffer.from(String)
console.log(Buffer.from('eric'));
// 5、Buffer.byteLength:返回字符串的字节长度
console.log(Buffer.byteLength('eric'));
// 6、Buffer.isBuffer(obj):判断是不是buffer
console.log(Buffer.isBuffer({})); //false
console.log(Buffer.isBuffer(Buffer.alloc(10))); //true
// 7、Buffer.concat(list):合并buffer
const buff1 = Buffer.from([1, 2, 3])
const buff2 = Buffer.from([4, 5, 6])
console.log(Buffer.concat([buff1, buff2]));
Buffer类上常⽤的属性、⽅法
Buffer.byteLength: 返回字符串的字节⻓度
Buffer.isBuffer(obj): 判断是否是buffer
Buffer.concat(list[, totalLength]): 合并buffer
官⽹⽂档地址:http://nodejs.cn/api/buffer.html
第2集 Buffer缓冲器常⽤api (⼆)
简介:介绍buffer缓冲器实例常⽤的api使⽤
buffer实例常⽤的属性、⽅法
buf.write(string[, offset[, length]][, encoding]) 将字符写⼊buffer,返回已经写⼊的字节 数
buf.fill(value[, offset[, end]][, encoding]) 填充buffer
buf.length buffer的⻓度
buf.toString([encoding[, start[, end]]]) 将buffer解码成字符串形式
buf.toJSON 返回 buffer 的 JSON 格式
buf.equals(otherBuffer) 对⽐其它buffer是否具有完全相同的字节
buf.indexOf/lastIndexOf 查找指定的值对应的索引
buf.slice([start[, end]]) 切割buffer
buf.copy(target[, targetStart[, sourceStart[, sourceEnd]]]) 拷⻉buffer
第3集 node.js⽂件系统模块常⽤api操作(⼀)
引⼊⽂件系统模块fs
const fs=require('fs')
fs.readFile(path[, options], callback) 读取⽂件
// 1、导入文件系统模块
const fs = require('fs')
// 2、读入文件
// fs.readFile('./hello.txt', (err, data) => {
// if (err) throw err;
// console.log(data.toString());
// })
fs.readFile('./hello.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
})
fs.writeFile(file, data[, options], callback) 写⼊⽂件
// 3、写入文件 writeFile 新写入的内容会覆盖原来的内容
fs.writeFile('./hello.txt', 'this is a test', err => {
if (err) throw err;
console.log("写入成功");
})
fs.appendFile(path, data[, options], callback) 追加数据到⽂件
// 4、追加数据 appendFile 追加数据到源文件里
const buf = Buffer.from('eric')
fs.appendFile('./hello.txt', buf, err => {
if (err) throw err;
console.log("追加成功");
})
fs.stat(path[, options], callback) 获取⽂件信息,判断⽂件状态(是⽂件还是⽂件夹)
// 5、判断文件的状态 stat 是文件还是文件夹
fs.stat('./hello.txt', (err, stats) => {
if (err) {
console.log("文件不存在");
return;
}
console.log(stats);
console.log(stats.isFile());
console.log(stats.isDirectory());
})
fs.rename(oldPath, newPath, callback) 重命名⽂件
// 6、重命名文件 rename
fs.rename('./hello.txt', './test.txt', err => {
if (err) throw err;
console.log("重命名成功");
})
fs.unlink(path, callback) 删除⽂件
// 7、删除文件 unlink
fs.unlink('./hello.txt', err => {
if (err) {
console.log("删除失败");
return
};
console.log("删除成功");
})
第4集 node.js⽂件系统模块常⽤api操作(⼆)
简介:讲解如何使⽤⽂件系统操作⽂件夹
fs.mkdir(path[, options], callback) 创建⽂件夹
// 2、创建文件夹[非递归]
// fs.mkdir('./a', err => {
// if (err) throw err;
// console.log("创建文件夹成功");
// })
// 创建文件夹[递归]
fs.mkdir('./b/a', {
recursive: true
}, err => {
if (err) throw err;
console.log("递归创建文件夹成功!");
})
fs.readdir (path[, options], callback) 读取⽂件夹
// 3、读取文件夹 readdir
fs.readdir('./', {
encoding: 'buffer',//文件名变成buffer
withFileTypes: true//文件的类型
}, (err, files) => {
if (err) throw err;
console.log(files);
})
fs.rmdir(path[, options], callback) 删除⽂件夹
// 4、删除文件夹 rmdir
fs.rmdir('./b', {
recursive: true
}, err => {
if (err) throw err;
console.log("删除文件夹成功");
})
fs.watch(filename[, options][, listener]) 监听文件和文件夹 【容易出现2次出现】
// 5、监听文件夹和文件的变动 watch
fs.watch('./', {
recursive: true
}, (eventType, filename) => {
console.log(eventType, filename);
})
监听⽂件变化 chokidar
先进行初始化
npm init -y
安装chokidar
npm install chokidar --save-dev
Chokidar.watch(path,[options])
/ 6、监听文件夹和文件最好的方法 chokidar
conkidar.watch('./', {
ignored: './node_modules'
}).on('all', (event, path) => {
console.log(event, path);
})
第5集 核⼼知识之⽂件流讲解
简介:讲解如何创建读取⽂件流和创建写⼊⽂件流
- Node.js 中有四种基本的流类型:
创建读取⽂件流fs.createReadStream(path[, options])
// 1、引入文件系统模块
const fs = require('fs')
//2、创建读取文件流
const rs = fs.createReadStream('./index.js', {
highWaterMark: 100
})
//进行计数
let count = 1;
//3、对文件流读取进行监听
//文件是一段段读取的,可以设置每次读取的最大值
rs.on('data', chunk => {
console.log(chunk.toString());
console.log(count++);
})
// 4、 对文件流结束进行监听
rs.on('end', () => {
console.log("读取结束");
})
创建写⼊⽂件流fs.createWriteStream(path[, options])
// 1、引入文件系统模块
const fs = require('fs')
//2、创建写入文件流
const ws = fs.createWriteStream('./a.txt')
let num = 1;
let timer = setInterval(() => {
if (num < 10) {
//参数必须是Buffer或者字符串
ws.write(num + '')
num++
} else {
ws.end('写入完成')
clearInterval(timer)
}
}, 200)
//3、监听写入结束
ws.on('finish', () => {
console.log("写入完成");
})
管道流
从数据流来源中⼀段⼀段通过管道流向⽬标。
// 管道流
const fs = require('fs')
//1、创建读入文件流
let rs = fs.createReadStream('./index.js')
let ws = fs.createWriteStream('./a.txt')
rs.pipe(ws)
第6集 基础模块path常⽤api
简介:讲解path模块常⽤的⼀些api
const { basename, dirname, extname, join, normalize, resolve, parse, format, sep, win32 } = require('path')
// // 1、path.basename 返回path的最后一部分,如果带上后缀名,前面的最后一部分就不显示后缀名
// console.log(path.basename('nodejs/2-6/index.js'));
// //2、path.dirname 返回该路径的目录
// console.log(path.dirname('nodejs/2-6/index.js'));
// // 3、path.extname 返回该文件的拓展名
// console.log(path.extname('index.js'));
// 1、path.basename 返回path的最后一部分,如果带上后缀名,前面的最后一部分就不显示后缀名
console.log(basename('nodejs/2-6/index.js'));
//2、path.dirname 返回该路径的目录
console.log(dirname('nodejs/2-6/index.js'));
// 3、path.extname 返回该文件的拓展名
console.log(extname('index.js'));
// 4、path.join 路径的拼接
console.log(join('nodejs', '1.txt'));
//5、path.normalize 规划化路径
console.log(normalize('nodejs//1.txt'));
console.log(normalize('/a/b/../nodejs//1.txt'));
// 6、path.resolve 显示绝对路径
console.log(resolve('./index.js'));
// 7、path.parse() 将路径转为对象
console.log(parse('nodejs/index.js'));
// 8、path.format() 将对象转为路径
console.log(format({
root: '/',
dir: 'nodejs',
base: 'a.txt'
}));
// 9、path.sep 返回当前系统下的分隔符
console.log(sep);
// 10、path.win32 window系统
console.log(win32.sep)
// 11、当前运行的文件名 __filename
console.log(__filename);
// 12、当前文件所在的目录 __dirname
console.log(__dirname);
console.log(resolve('index.js'));
注意: resolve和__filename的区别
如果运行的时候是在2-6下执行的
console.log(__filename);//D:\study\web\node\node\2-6\index.js
console.log(resolve('index.js'));//D:\study\web\node\node\2-6\index.js
如果运行的时候,切到上一级目录
cd ..
node 2-6/index.js
console.log(__filename);//D:\study\web\node\node\2-6\index.js
console.log(resolve('index.js'));//D:\study\web\node\node\index.js[不一样!!!]
第7集 深度讲解node.js事件触发器
简介:讲解事件触发器events的使⽤⽅法
const EventEmitter = require('events')
class MyEmitter extends EventEmitter {}
let myEmitter = new MyEmitter()
// 1、注册监听器
//有参
// myEmitter.on('hi', (a, b) => {
// console.log("触发了有参事件", a + b);
// })
// myEmitter.on('hi', () => {
// console.log('触发了无参事件');
// })
function fn1(a, b) {
console.log("触发了有参事件", a + b);
}
function fn2() {
console.log('触发了无参事件');
}
myEmitter.on('hi', fn1)
myEmitter.on('hi', fn2)
//注册 once只能触发一次
myEmitter.once('hello', () => {
console.log("只能触发一次的事件");
})
myEmitter.emit('hello')
// 3、移除触发器
myEmitter.removeListener('hi', fn1)
// 2、触发监听器
myEmitter.emit('hi', 2, 3)
//移除所有触发器
myEmitter.removeAllListeners('hi')
myEmitter.emit('hi')
第8集 核⼼模块util常⽤⼯具
简介:讲解util模块⾥常⽤的⼯具
util.callbackify(original) 将 async 异步函数(或者⼀个返回值为 Promise 的函数)转换成遵 循异常优先的回调⻛格的函数
const util = require('util');
async function hello(){
return 'hello world'
}
let helloCb = util.callbackify(hello);
helloCb((err,res) => {
if(err) throw err;
console.log(res)
})
util.promisify(original) 转换成 promise 版本的函数
const util = require('util')
const fs = require('fs')
// util.promisify(original) 转换成 promise 版本的函数 避免了回调地狱
//将文件的类型信息函数转为promise函数
let stat = util.promisify(fs.stat)
// stat('./index2.js').then(data => {
// console.log(data);
// }).catch(err => {
// console.log(err);
// })
async function fn1() {
try {
let stats = await stat('./index2.js')
console.log(stats);
} catch (e) {
console.log(e);
}
}
fn1()
util.types.isDate(value) 判断是否为date数据
console.log(util.types.isDate(new Date()))