Created
September 1, 2018 06:05
-
-
Save angelochen960/d1eeaf761e2504876919e7ade9697235 to your computer and use it in GitHub Desktop.
use dirty db in a module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
first, create a mydb.js | |
``` | |
var dirty = require('dirty'); | |
let MyDB = class { | |
constructor(dbname) { | |
this.dbname = dbname | |
} | |
// Method | |
open() { | |
this.db = dirty(this.dbname) | |
return new Promise((resolve, reject) => { | |
this.db.on('load', function (length) { | |
console.log('loaded!') | |
resolve(length) | |
}) | |
}) | |
} | |
get_all_items() { | |
return new Promise((resolve, reject) => { | |
let ret = [] | |
this.db.forEach(function (key, val) { | |
ret.push({ [key]: val }) | |
}); | |
resolve(ret) | |
}) | |
} | |
} | |
exports.MyDB = MyDB | |
``` | |
now, use it in another file: | |
``` | |
"use strict" | |
const Mydb = require("./mydb").MyDB | |
var mydb = new Mydb('../data/items.db') | |
console.log('mydb', mydb); | |
(async function () { | |
try { | |
var rslt = await mydb.open() | |
console.log('rslt', rslt) | |
var all = await mydb.get_all_items() | |
console.log(all) | |
} | |
catch (err) { | |
console.log('error', err) | |
} | |
}()); | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment