梗概:
- 导入
node:fs/promises - 用
open()创建FileHandle实例- 执行读写操作完成之后, 一定要记得关闭文件
获取路径信息语法:
stat('路径')
1. 返回值:
返回Stat对象, 具有以下方法与属性:
interface Stat{
isFile(): boolean;//判断路径是否文件
isDirectory(): boolean;//判断路径是否是目录
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
dev: T;
ino: T;
mode: T;
nlink: T;
uid: T;
gid: T;
rdev: T;
size: T;
blksize: T;
blocks: T;
atimeMs: T;
mtimeMs: T;
ctimeMs: T;
birthtimeMs: T;
atime: Date;
mtime: Date;
ctime: Date;
birthtime: Date;
}文件操作语法:
1. open()
open(目标, 行为[, 模式])
1.1. 注意:
- 有些文件(如json), 使用w的行为(w或w+)打开, 会清空文件内容
- 所以读取的时候, 不要使用w行为打开, 要使用r行为
2. 关闭文件:
filehandle.close()
2.1. 说明:
- 手动关闭文件, 防止内存泄漏等不安全事情发生
- 虽然默认是自动关闭的, 但那是不稳定的
3. 创建流:
3.1. 创建读取流:
filehandle.createReadStream([参数对象])
参数对象是可选的, 有六个属性:
注意:
- 当读取流发出
end事件的时候, 会自动关闭filehandle
3.2. 创建写入流:
filehandle.createWriteStream([参数对象])
参数对象时可选的, 有六个属性:
4. 读取Buffer
filehandle.read(buffer, 写入buffer的位置, 读取长度, 读取位置)
读取位置如果为null, 则为当前光标位置
4.1. 返回值:
Promise对象
- 传给resolve的是一个对象, 有两个属性:
bytesRead: 读取长度buffer: 读取出来的buffer
5. 读取字符串:
5.1. 语法一:
filehandle.readFile('编码格式')
5.2. 语法二:
filehandle.readFile(设置对象)
设置对象有两个属性:encoding默认为nullsignal是否允许异常终止
5.3. 说明:
6. 写入Buffer:
filehandle.write(buffer, buffer的起始位置[, 写入长度[, 写入位置]])
写入长度默认为buffer.byteLength - offset写入位置默认为最后
6.1. 返回值:
Promise对象
- 传给resolve的是一个对象, 有两个属性:
bytesWritten: 写入长度buffer: 写入的buffer
6.2. 说明:
- On Linux, positional writes do not work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
7. 按字节写入字符串:
filehandle.write('字符串'[, 写入位置[, '编码格式']])
写入位置单位为字节, 而不是字符
7.1. 返回值:
Promise对象
- 传给resolve的是一个对象, 有两个属性:
bytesWritten: 写入长度buffer: 写入的 string
8. 替换整个文本:
filehandle.writeFile('字符串'或buffer[,{encoding:'编码格式'}])
- 当写入字符串时, 才需要提供编码格式
目录操作语法:
1. 读取目录的内容
read(路径[, 参数对象])
参数对象有两个参数:encoding:string, 返回文件名的编码格式- 如果设置位
'buffer', 则返回值得文件名就是buffer类型
- 如果设置位
withFileTypes:boolean, 影响返回数组的元素类型
1.1. 返回值:
返回一个数组, 每一个元素代表了一个文件或目录
- 如果
withFileTypes为真, 则元素为Dirent类型 - 如果
withFileTypes为假, 则元素为string类型, 为目录或文件名(包含拓展名)
1.2. 说明:
- 只能读取一层
- 常常配合path模块的路径拼接api来获取该目录下的文件路径