读取文件
- readFile 读取文件全部内容,如果文件不存在则报错
- fs.read 方法可以更精确的读取文件
import { readFile } from "node:fs/promises";
readFile("./test.json", "utf-8").then((res) => {
console.log("res>>>", JSON.parse(res));
});
写入文件
- writeFile 如果文件不存在会创建一个文件,这种写入方式会全部删除旧有的数据,然后再写入数据
- appendFile 往文件中添加数据
- fs.write 方法可以更精确写入内容
import { writeFile, appendFile } from "node:fs/promises";
const obj = { a: 1, b: 2 };
writeFile("./test.json", JSON.stringify(obj, null, 2)).then((res) => {
console.log("res2", res);
});
appendFile("./test.txt", "\n我是zfy").then((res) => {
console.log("res", res);
});
拷贝文件
- fsPromises.copyFile(src, dest[, mode])
import { copyFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
copyFile("test.txt", path.resolve(__dirname, "../test2.txt")).then((res) => {
console.log("res", res);
});
删除文件
- fsPromises.rm(path[, options])
import { rm } from "node:fs/promises";
rm("./test.txt", { force: true, recursive: true }).then((res) => {
console.log("res", res);
});
创建文件夹
- fsPromises.mkdir(path[, options])
import { mkdir } from "node:fs/promises";
mkdir(path.resolve(__dirname, "../test")).then((res) => {
console.log("res", res);
});
读取文件夹
- fsPromises.readdir(path[, options]) defaultOptions = {encoding: 'utf8', withFileTypes: false}
import { readdir } from "node:fs/promises";
const dirPath = path.resolve(__dirname, "../test");
readdir(dirPath).then((files) => {
for (const file of files) {
console.log(file);
}
});
拷贝文件或文件夹里面内容(只会拷贝内容), 路径不存在时会自动创建
- fsPromises.cp(src, dest[, options]) node v16.17 才支持
import { cp } from "node:fs/promises";
cp(path.resolve(__dirname), path.resolve(__dirname, "../test2"), {
force: true,
recursive: true,
});
获取文件或文件夹信息
- fsPromises.stat(path[, options])
import { stat } from "node:fs/promises";
stat("./test.js").then((res) => {
console.log(file, res.isFile());
});
判断文件或文件夹是否存在、文件是否有权限
- fsPromises.access(path[, mode])#
import { access, constants } from "node:fs/promises";
access("./test", constants.F_OK)
.then(() => {
console.log("exit");
})
.catch(() => {
console.log("not");
});