has #9
3 changed files with 30 additions and 13 deletions
5
.gitignore
vendored
5
.gitignore
vendored
|
@ -1,3 +1,8 @@
|
|||
node_modules
|
||||
package-lock.json
|
||||
build
|
||||
|
||||
*yarn*
|
||||
*.tsbuildinfo
|
||||
tsconfig.tsbuildinfo
|
||||
*test*
|
11
readme.md
11
readme.md
|
@ -4,7 +4,7 @@ MapDB A Map that stores data locally and loads it at startup. Written in JavaScr
|
|||
|
||||
### How does it work?
|
||||
|
||||
Map.db works just like the JavaScript built-in **Map**, with the same methods and functionalities, and in fact it uses itself a Map, but while the built-in Map only stores data in internal memory, this module **stores data locally in a file and loads it back in the Map at startup**.
|
||||
Mit.db works just like the JavaScript built-in **Map**, with the same methods and functionalities, and in fact it uses itself a Map, but while the built-in Map only stores data in internal memory, this module **stores data locally in a file and loads it back in the Map at startup**.
|
||||
|
||||
The purpose of this module is to make the JavaScript built-in Map an actual **database**, and there comes the name `mit.db`: a Map that can be used as a database.
|
||||
|
||||
|
@ -58,5 +58,12 @@ await db.set('what', 'how')
|
|||
#### get()
|
||||
|
||||
```js
|
||||
var answ = db.get('what') // answ = how
|
||||
var ansa = db.get('what') // ansa = how
|
||||
```
|
||||
|
||||
#### has()
|
||||
|
||||
```js
|
||||
var ansb = db.has('what') // ansb = true
|
||||
var ansc = db.has('attila') // ansc = false
|
||||
```
|
||||
|
|
25
src/index.ts
25
src/index.ts
|
@ -8,10 +8,10 @@ writeDB = fsp.writeFile;
|
|||
export class MitDB {
|
||||
/**
|
||||
* @constructor
|
||||
* @param filename If not set, MapDB will only use internal memory
|
||||
* @param filename If not set, MitDB will only use internal memory
|
||||
* @example 'file.db'
|
||||
* @param options Options to pass to the constructor
|
||||
* @param options.dirname
|
||||
* @param options.dirname Where to save the file?
|
||||
* @example 'data'
|
||||
*/
|
||||
constructor(fn: string | undefined, options: any) {
|
||||
|
@ -58,15 +58,20 @@ export class MitDB {
|
|||
/**
|
||||
* @param key
|
||||
*/
|
||||
|
||||
get(key: string | number) {
|
||||
if (map) {
|
||||
return map.get(key)
|
||||
} else {
|
||||
file = fs.readFileSync(db);
|
||||
data = JSON.parse(file.toString());
|
||||
file = fs.readFileSync(db);
|
||||
data = JSON.parse(file.toString());
|
||||
|
||||
return data.find((pair: any) => pair.key == key)?.value || undefined;
|
||||
}
|
||||
return data.find((pair: any) => pair.key == key)?.value || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key
|
||||
*/
|
||||
has(key: string | number) {
|
||||
const file = fs.readFileSync(db);
|
||||
const data = JSON.parse(file.toString());
|
||||
|
||||
return data.find((pair: any) => pair.key == key) ? true : false;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue