【笔记】Nodejs的文件读写

前言

Nodejs通过fs模块实现文件读写

在使用相对路径时,Nodejs会先将相对路径转换为绝对路径,再通过绝对路径读写文件

引入依赖

1
const fs = require("fs");

flag选项

参数 读写选项 是否为二进制 文件不存在是否报错 文件指针位置
r 只读 报错 文件首部
r+ 读写 报错 文件首部
w 写入 新建文件 文件首部
w+ 读写 新建文件 文件首部
a 写入 新建文件 文件尾部
a+ 读写 新建文件 文件尾部

打开文件

fd:文件描述符

1
2
3
fs.open("<file>", function (err, fd) {
...
});

通过文件描述符获取文件信息

1
2
3
4
5
fs.open("<file>", function (err, fd) {
fs.fstat(fd, function (err, stats) {
console.log(stats);
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Stats {
dev: 0,
mode: 0,
nlink: 1,
uid: 0,
gid: 0,
rdev: 0,
blksize: 0,
ino: 0,
size: 0,
blocks: 0,
atimeMs: 0.0,
mtimeMs: 0.0,
ctimeMs: 0.0,
birthtimeMs: 0.0
}

关闭文件

1
2
3
4
5
fs.open("<file>", function (err, fd) {
fs.close(fd, function (err) {
...
});
});

同步

读文件

1
const buffer = fs.readFileSync("<file>");

flag:访问模式,缺省值为r
encoding:编码,没有指定编码时,默认返回Buffer对象

1
2
3
4
const content = fs.readFileSync("<file>", {
flag: "r",
encoding: "UTF-8"
});

写文件(文件首部)

1
fs.writeFileSync("<file>", "<text>");

flag:访问模式,缺省值为w

1
2
3
fs.writeFileSync("<file>", "<text>", {
flag: "w"
});

写文件(文件尾部)

1
fs.appendFileSync("<file>", "<text>");

flag:访问模式,缺省值为a

1
2
3
fs.appendFileSync("<file>", "<text>", {
flag: "a"
});

异步(通过回调函数)

读文件

1
2
3
fs.readFile("<file>", function (err, data) {
...
});

flag:访问模式,缺省值为r
encoding:编码,没有指定编码时,默认返回Buffer对象

1
2
3
4
5
6
fs.readFile("<file>", {
flag: "r",
encoding: "UTF-8"
}, function (err, data) {
...
});

写文件(文件首部)

1
2
3
fs.writeFile("<file>", "<text>", function (err) {
...
});

flag:访问模式,缺省值为w

1
2
3
4
5
fs.writeFile("<file>", "<text>", {
flag: "w"
}, function (err) {
...
});

写文件(文件尾部)

1
2
3
fs.appendFile("<file>", "<text>", function (err) {
...
});

flag:访问模式,缺省值为a

1
2
3
4
5
fs.appendFile("<file>", "<text>", {
flag: "a"
}, function (err) {
...
});

异步(通过Promise对象)

读文件

1
2
3
4
5
fs.promises.readFile("file").then(function (data) {
...
}).catch(function (err) {
...
});

flag:访问模式,缺省值为r
encoding:编码,没有指定编码时,默认返回Buffer对象

1
2
3
4
5
6
7
8
fs.promises.readFile("file", {
flag: "r",
encoding: "UTF-8"
}).then(function (data) {
...
}).catch(function (err) {
...
});

写文件(文件首部)

1
2
3
fs.promises.writeFile("<file>", "<text>").catch(function (err) {
...
});

flag:访问模式,缺省值为w

1
2
3
4
5
fs.promises.writeFile("<file>", "<text>", {
flag: "w"
}).catch(function (err) {
...
});

写文件(文件尾部)

1
2
3
fs.promises.appendFile("<file>", "<text>").catch(function (err) {
...
});

flag:访问模式,缺省值为a

1
2
3
4
5
fs.promises.appendFile("<file>", "<text>", {
flag: "a"
}).catch(function (err) {
...
});

完成