Node.js中fs模塊實現(xiàn)配置文件的讀寫操作
Node.js中fs模塊實現(xiàn)配置文件的讀寫
在Node.js中, fs模塊提供了對文件系統(tǒng)的訪問功能,我們可以利用它來實現(xiàn)配置文件的讀取和寫入操作。正好用到,就記錄一下。
準(zhǔn)備工作
確保你的項目目錄已經(jīng)安裝了做了npm或pnpm或yarn等node相關(guān)初始化,存在node_modules文件夾,這樣就可以使用fs:
const fs = require('fs');接下來就是定義路徑,我是用到年月來定義路徑,并放在當(dāng)前路徑的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}`);
// 獲取當(dāng)前日期
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 };
}讀取配置
要實現(xiàn)讀取的邏輯,首先要做下文件夾排空報錯處理,!fs.existsSync(folderPath)假如路徑不存在,那代表文件也不存在,mkdirp(folderPath);根據(jù)路徑創(chuàng)建文件夾,再 fs.writeFileSync(aFilePath, '{}');創(chuàng)建文件。假如存在路徑,!fs.existsSync(aFilePath)文件不存在,創(chuàng)建文件:
function CheckPathOrFiles() {
if (!fs.existsSync(folderPath)) {
mkdirp(folderPath);
fs.writeFileSync(aFilePath, '{}');
} else {
if (!fs.existsSync(aFilePath)) {
console.log(`創(chuàng)建文件:${aFilePath}`);
fs.writeFileSync(aFilePath, '{}');
}
}
}
function mkdirp(dir) {
if (fs.existsSync(dir)) { return true; }
const dirname = path.dirname(dir);
mkdirp(dirname); // 遞歸創(chuàng)建父目錄
fs.mkdirSync(dir);
}在上面的代碼中,我重構(gòu)了mkdirp函數(shù)來創(chuàng)建空文件夾,而沒有使用fs自帶的mkdirSync(),使用后報錯Error: ENOENT: no such file or directory.Object.fs.mkdirSync,大致原因就是node.js低版本的漏洞吧,你也可以嘗試直接使用下面代碼代替mkdirp(folderPath);試試。
fs.mkdirSync(folderPath, { recursive: true }); // 遞歸創(chuàng)建路徑然后編寫讀取函數(shù)getHostConfigs(),通過fs.readFileSync(aFilePath, 'utf8')獲取到aFilePath該文件路徑下的文件:
function getHostConfigs() {
console.log('進入讀取環(huán)節(jié)..')
try {
CheckPathOrFiles()
// 讀取文件配置
const data = fs.readFileSync(aFilePath, 'utf8');
const hostConfigs = JSON.parse(data);
console.log('配置校驗成功!!');
return hostConfigs;
} catch (error) {
console.error('讀取失敗:', error);
return null;
}
}接下來是配置的更新寫入,這部分可以根據(jù)自己需求來,比較重要的是let hostConfigs = getHostConfigs();讀取配置,然后在這個函數(shù)里利用fs.writeFile(aFilePath,data)實現(xiàn)寫入邏輯:
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);
}最后導(dǎo)出模塊,方便其他腳本使用:
module.exports = {
updateHostConfigs,
getHostConfigs
};到此這篇關(guān)于Node.js中fs模塊實現(xiàn)配置文件的讀寫的文章就介紹到這了,更多相關(guān)Node.js fs模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
nodejs實現(xiàn)百度輿情接口應(yīng)用示例
這篇文章主要介紹了nodejs實現(xiàn)百度輿情接口應(yīng)用,結(jié)合實例形式分析了node.js調(diào)用百度輿情接口的具體使用技巧,需要的朋友可以參考下2020-02-02

