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 };
到此这篇关于node.js中fs模块实现配置文件的读写的文章就介绍到这了,更多相关node.js fs模块内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论