欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > nodejs,本地轻量localstorage

nodejs,本地轻量localstorage

2024/10/24 16:21:47 来源:https://blog.csdn.net/oNuoZuo/article/details/112653651  浏览:    关键词:nodejs,本地轻量localstorage

真的没必要npm搞一堆功能特别多的库,自己简单封装了一个

mod代码

const fs = require('fs');
const path = require('path');class JsonFileStorage {constructor(filePath) {this.filePath = filePath;let data = '{}';try {data = fs.readFileSync(this.filePath, 'utf8');this.lastModified = fs.statSync(this.filePath).mtime;} catch (error) {// 文件不存在或读取失败,初始化空对象。this.lastModified = 0;}this.data = JSON.parse(data);}get(key, def = null) {const currentStat = fs.statSync(this.filePath);if (currentStat.mtime !== this.lastModified) {// 文件已被修改,重新加载数据。this.data = JSON.parse(fs.readFileSync(this.filePath, 'utf8'));this.lastModified = currentStat.mtime;}if (this.data[key]) {return this.data[key];}return def;}// 快速获取数据,不检查文件是否被修改。getQuick(key, def = null) {if (this.data[key]) {return this.data[key];}return def;}set(key, data) {this.data[key] = data;this.save();}save() {fs.writeFileSync(this.filePath, JSON.stringify(this.data, null, 2), 'utf8');this.lastModified = fs.statSync(this.filePath).mtime;}
}module.exports = JsonFileStorage;

使用示例

const JsonFileStorage = require('./jsonFileStorage');const storage = new JsonFileStorage('data.json');
storage.set('testKey', { value: 'testValue' });
console.log(storage.get('testKey'),storage.getQuick('testKey'));

使用说明

1. set(key,data)  是设置内容的,内容可以传递进去任何js基础数据类型

2. get(key)  默认会重新读取一下json,保证最新,但是性能会差一点点(取决于你的磁盘速度,非常一点点)

3. getQuick(key)  直接内存读取参数,非常非常快,对于你不会手动从磁盘编辑的设置项目,可以用getQuick

其他解决方案

如果你需要比较成熟的方案,更多的功能处理配置项,可以考虑:fs-extra,lowdb,configstore

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com