const fs=require('fs-extra');
const ShortName=require('./ShortName');
const WashRoom=require('./WashRoom')
//本地数据库
class LocalStorage{
constructor(tagDir) {
this.dbDir=tagDir||__dirname+'/db/';
fs.ensureDirSync(this.dbDir);
this.shortName=new ShortName({
tagDir:this.dbDir+'shortName/',
})
}
async setItem(name,item){
const id=await this.shortName.saveId(name);
const wash=new WashRoom(id);
await wash.wait();
fs.writeFileSync(this.dbDir+id,item);
wash.end();
}
async setData (name, data) {
const item = typeof data === 'object' ? JSON.stringify(data) : data;
await this.setItem(name,item);
}
async getData (name) {
if (await this.hasData(name)) {
const id=await this.shortName.getId(name);
const item=fs.readFileSync(this.dbDir+id).toString()
try {
return JSON.parse(item);
} catch (e) {
// ..
}
return item;
}
}
async hasData (name) {
const id=await this.shortName.getId(name);
if(id!==-1&&fs.existsSync(this.dbDir+id)){
return true
}
return false;
}
async removeData (name) {
const id=await this.shortName.getId(name);
fs.unlinkSync(this.dbDir+id);
}
clearData () {
fs.emptyDirSync(this.dbDir);
fs.ensureDirSync(this.dbDir+'shortName/');
}
}
module.exports=LocalStorage;
const LocalStorage = require('./utils/LocalStorage');
const localStorage=new LocalStorage(__dirname+'/localDb/');
localStorage.setData('首页',{
'logo':'png1',
'标题':'我是淀粉酶'
})
localStorage.getData('首页').then(function (d) {
console.log(d)
})