万维网包括哪些网站,中企动力邮箱登陆,pageadmin仿站教程,vue做的网站影响收录么Node.js中fs模块实现配置文件的读写 准备工作读取配置 在Node.js中#xff0c;
fs模块提供了对文件系统的访问功能#xff0c;我们可以利用它来实现配置文件的读取和写入操作。正好用到#xff0c;就记录一下。 准备工作
确保你的项目目录已经安装了做了npm或pnpm或yarn等… Node.js中fs模块实现配置文件的读写 准备工作读取配置 在Node.js中
fs模块提供了对文件系统的访问功能我们可以利用它来实现配置文件的读取和写入操作。正好用到就记录一下。 准备工作
确保你的项目目录已经安装了做了npm或pnpm或yarn等node相关初始化存在node_modules文件夹这样就可以使用fs
const fs require(fs);接下来就是定义路径我是用到年月来定义路径并放在当前路径的storeConfigs下:
const path require(path);
const date getDate();// 文件夹路径 ./storeConfigs/${date.year}/${date.month}
const folderPath path.resolve(__dirname, storeConfigs, ${date.year}, ${date.month});// 用date.day来定义文件名 ./storeConfigs/${date.year}/${date.month}/${date.day}
const aFilePath path.resolve(folderPath, ${date.day});// 获取当前日期
function getDate() {const currentDate new Date();const year currentDate.getFullYear();const month currentDate.getMonth() 1;const day currentDate.getDate();return { year: year, month: month, day: day };
}读取配置
要实现读取的逻辑首先要做下文件夹排空报错处理!fs.existsSync(folderPath)假如路径不存在那代表文件也不存在mkdirp(folderPath);根据路径创建文件夹再 fs.writeFileSync(aFilePath, {});创建文件。假如存在路径,!fs.existsSync(aFilePath)文件不存在创建文件:
function CheckPathOrFiles() {if (!fs.existsSync(folderPath)) {mkdirp(folderPath);fs.writeFileSync(aFilePath, {});} else {if (!fs.existsSync(aFilePath)) {console.log(创建文件${aFilePath});fs.writeFileSync(aFilePath, {});}}
}
function mkdirp(dir) {if (fs.existsSync(dir)) { return true; }const dirname path.dirname(dir);mkdirp(dirname); // 递归创建父目录fs.mkdirSync(dir);
}在上面的代码中我重构了mkdirp函数来创建空文件夹而没有使用fs自带的mkdirSync()使用后报错 Error: ENOENT: no such file or directory.Object.fs.mkdirSync,大致原因就是node.js低版本的漏洞吧你也可以尝试直接使用下面代码代替mkdirp(folderPath);试试。
fs.mkdirSync(folderPath, { recursive: true }); // 递归创建路径然后编写读取函数getHostConfigs(),通过fs.readFileSync(aFilePath, utf8)获取到aFilePath该文件路径下的文件
function getHostConfigs() {console.log(进入读取环节..)try {CheckPathOrFiles()// 读取文件配置const data fs.readFileSync(aFilePath, utf8);const hostConfigs JSON.parse(data);console.log(配置校验成功);return hostConfigs;} catch (error) {console.error(读取失败:, error);return null;}
}接下来是配置的更新写入这部分可以根据自己需求来,比较重要的是let hostConfigs getHostConfigs();读取配置然后在这个函数里利用fs.writeFile(aFilePath,data)实现写入逻辑
function updateHostConfigs(config) {let hostConfigs getHostConfigs();if (!hostConfigs) {hostConfigs {};}if (config.host) {hostConfigs[config.host] config;}// 写入配置fs.writeFile(aFilePath, JSON.stringify(hostConfigs), (err) {if (err) {console.error(写入出错:, err);} else {console.log(配置写入成功..);}});console.log(hostConfigs);
}最后导出模块方便其他脚本使用
module.exports {updateHostConfigs,getHostConfigs
};