记录学习nodejs的第一天~
fs文件读取
文件读取常用的三种方式~
一、同步读取:会阻塞后面代码的执行(很少用)
使用fs.readFileSync()方法,该方法接受两个参数
- path:文件路径
- options(可选):配置对象:{
encoding:'设置编码模式',flag:指定文件打开的模式和行为}
const fs = require('fs');
// `fs.readFileSync(path[, options])`
const res = fs.readFileSync("./abc.txt",{ encoding:'utf-8'});
console.log('后续代码~')
二、异步读取:回调函数的方法
// `fs.readFile(path[, options], callback)`
fs.readFile('./abc.txt',{ encoding:'utf-8' },(err,data)=>{
if(err) {
console.log('文件读取错误:',err)
} else {
console.log("读取文件结果:", data);
}
})
console.log('后续代码~')
三、异步读取:Promise的方式
fs.promises
.readFile("./abc.txt", { encoding: "utf-8" })
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
fs文件描述符的使用
Node.js 使用文件描述符(File Descriptor,简称 FD)来引用文件和其他输入/输出资源。文件描述符是一个抽象层,用于简化对不同类型资源的访问,这些资源可以是实际的文件、套接字、管道等。在 Node.js 中,文件描述符主要用于以下几个方面:
- 文件操作:在进行文件读写操作时,Node.js 会使用文件描述符。例如,使用
fs.open打开文件时,会返回一个文件描述符,该文件描述符随后可以用于fs.read、fs.write等操作。 - 网络通信:Node.js 中的网络通信也依赖于文件描述符。每个 TCP 连接都可以用一个文件描述符来表示,这使得使用
net模块进行网络编程时可以采用与文件 I/O 相似的 API。 - 标准流:Node.js 的标准输入(
process.stdin)、标准输出(process.stdout)和标准错误(process.stderr)都是以文件描述符为基础的特殊类型。 - 事件循环:Node.js 的事件循环机制允许非阻塞的 I/O 操作,文件描述符在这一机制中扮演了重要角色。当一个 I/O 操作开始时,Node.js 会将请求放入事件循环中,并在操作完成时通过回调函数来处理结果。
- 性能优化:合理管理文件描述符对于性能优化很重要。文件描述符是有限资源,如果不正确管理(例如,打开文件后没有正确关闭),可能会导致资源泄露。
const fs = require("fs");
fs.open("./bbb.txt", (err, fd) => {
if (err) {
return;
}
// 1.获取文件描述符
console.log(fd);
// 2.读取文件信息
fs.fstat(fd, (err, stat) => {
if (err) return;
console.log(stat);
});
// 3.手动关闭文件
fs.close(fd, (err) => {
if (err) {
return;
}
console.log("文件关闭成功");
});
});
fs文件写入的api
const fs = require("fs");
const content = "\n我是写入的内容 hello world;";
// 文件写入操作
fs.writeFile("./ccc.txt", content, { encoding: "utf-8", flag: "a" }, (err) => {
if (err) {
console.log("文件写入错误:", err);
} else {
console.log("文件写入成功");
}
});
fs文件夹创建、重命名
// 创建文件夹
const fs = require("fs");
// 创建文件夹 directory
fs.mkdir("./test", (err) => {
console.log(err);
});
// 重命名
fs.rename("./test", "./new_test", (err) => {
if (err) return;
});
fs文件夹的读取操作
const fs = require("fs");
// 递归的读取文件夹中的所有文件
function readDirectory(path) {
fs.readdir(path, { withFileTypes: true }, (err, files) => {
if (err) {
return;
}
files.forEach((item) => {
// 判断是否是目录,如果是目录则递归调用
if (item.isDirectory()) {
readDirectory(`${path}/${item.name}`);
} else {
console.log("item是一个文件:", item.name);
}
});
});
}
readDirectory("./test");
这些就是我第一天学fs模块的一些常见的api~持续学习中