UNPKG

molly-db

Version:

Molly-db is a free and open source library for nodejs that allow you create a lightweight encrypted database using Json files

65 lines (48 loc) 2.81 kB
const crypto = require('./crypto_handler'); const fetch = require('molly-fetch'); const readline = require('readline'); const path = require('path'); const fs = require('fs'); const db = new Object(); /*--────────────────────────────────────────────────────────────────────────────────────────────--*/ function fillDB( _db, _table, _path, _pass ){ return new Promise(async(response,reject)=>{ let stream; if( fs.existsSync(_path) ) stream = fs.createReadStream(_path); else if( (/^http/).test(_path) ) stream = (await fetch(_path,{responseType:'stream'})).data; try { const _itr = readline.createInterface({ input: stream }); _itr.on('close',()=>{ response() }); _itr.on('line',(line)=>{ db[_db][_table].push(crypto.decrypt( line,_pass )); }); } catch(e) { return response(`error: reading ${_path}`) } }); } /*--────────────────────────────────────────────────────────────────────────────────────────────--*/ module.exports = function(args){ return new Promise(async(response,reject)=>{ try { const dir = `${args.path}/_init_.json`; if( !(/^http/).test(args.path) ) db._init_ = JSON.parse(fs.readFileSync(dir)); else db._init_ = (await fetch(dir)).data; db._path_ = args.path; for( let i in db._init_.DB ){ const DB = db._init_.DB[i]; const name = DB.name; delete db[name]; db[name] = new Object(); for( let j in DB.tables ){ const table = DB.tables[j]; const dir = `${db._path_}/${table}.json`; db[name][table] = new Array(); await fillDB( name,table,dir,args.pass ); } } } catch(e) { db._init_ = {DB:[]}; db._path_ = args.path; const dir = `${args.path}/_init_.json`; try { fs.writeFileSync( dir,JSON.stringify(db._init_) ); } catch(e) { } } response(db); }); } /*--────────────────────────────────────────────────────────────────────────────────────────────--*/