Buffer是用来存放内容的 (标识的是内存空间)
-
buffer声明方式需要指定大小
-
长度 指定buffer中存放的特定内容 我们可以直接给字符串
console.log(Buffer.alloc(3)); // node中的最小单位都是字节 console.log(Buffer.from([100, 200])); // 这种方式不常用 console.log(Buffer.from('帅'))
-
内存一但申请了,无法直接在原内存上进行扩展
-
在前端上传文件的时候(分片上传) 创建一个大的内存,来存储多段数据
-
合并数据(tcp分段传输的,我们肯定希望拿到数据后可以进行拼接操作
Buffer方法
- Buffer.alloc() 分配大小
- Buffer.from() 将内容转换成buffer
- Buffer.copy()
- Buffer.concat() 拼接
- buffer.slice() 截取内存 浅拷贝 截取的是内存空间,修改会影响原buffer
- toString() 转换成字符串
- buffer.length 是字节长度
- Buffer.isBuffer() 在node中处理数据 有字符串和buffer共存的情况,为了保证不出错,我们一般全部转换成buffer来处理
- buffer.split() 基于之前的方法封装
实现原型继承有几种方案
- obj.prototype.proto = parent.prototype
- obj.prototype = Object.create(parent.prototype)
- Object.setPrototypeOf( obj.prototype,parent.prototype)
文件读写
文件的读写 如果相对于内存来说的话 就是反过来的 读取文件其实是像内存中写入 , 要是写入内容,将数据读取出来
内存的空间是有限的,数据过大,都写入到内存(淹没可用内存) 64k以下的文件可以采用readFile
-
如果大文件 不能采用readFile来读取
-
node中提供了手动读取的方式 (api)
// 1) 打开 2)指定读取的位置 3) 关闭文件
// flags
// r: 我打开文件的目的是读取文件
// w; 我打开文件的目的是写入
// a: 我们打开文件是追加内容的append方法
// r+: 如果文件不存在会报错, 具备读取和写入的能
// w+: 如果文件不存在会创建, 具备读取和写入的能
// 权限位置 8禁止
// 二进制的组合 : 权限的组合 1用户的执行操作 2用户的写入操作 4用户的读取操作 位运算
// chmod -R 777
// 001 | 010 按位或可以将权限组合起来 011
// 001
// 010
// 100
// 111
// 001
// 010
// 100
// 1000
// 按照位来做组合 ,可以将权限组合起来
可读流
const fs = require('fs');
const EventEmitter = require('events')
class ReadStream extends EventEmitter{
constructor(path, options) {
super()
this.path = path;
this.flags = options.flags || 'r';
this.encoding = options.encoding || null;
this.mode = options.mode || 0o666;
this.autoClose = options.autoClose || true;
this.emitClose = options.emitClose || true;
this.start = options.start || 0;
this.end = options.end;
this.pos = this.start
this.flowing = false; // 非流动模式
this.highWaterMark = options.highWaterMark || 64 * 1024
// 这里是同步监听,用户绑定了data会立刻出发这个回调
this.on('newListener', (type) =>{
if (type === 'data') {
this.flowing = true;
this.read();
}
})
this.open()
}
destroy(err) {
if (this.fd) {
fs.close(this.fd,()=>this.emit('close'))
}
if (err) {
this.emit('error',err)
}
}
open() {
fs.open(this.path, this.flags, this.mode, (err,fd) => {
if (err) this.destroy(err