Simple database without dependencies in a single JavaScript file.
- opinionated: all objects have atleast
id
,created
andupdated
keys - minimalist: only 3 operations:
get
,set
anddel
- tiny: less than 100 LOC including comments and whitespace
Install with npm:
npm i -S https://github.com/eremt/db.js
or just download the file:
wget https://raw.github.com/eremt/db.js/main/db.js
const dbjs = require('db.js')
const db = new dbjs()
An optional file to use for data persistence, if it doesn't exist it will be created. If undefined
the storage will default to memory.
const dbjs = require('db.js')
const db = new dbjs({ file: './db.json' })
Without query
(or any falsy value such as null
, ''
, etc.) an array containing all items is returned.
db.get()
// => [ { id, created, updated, ... }, ... ]
If query
is a string
it is treated as the key
and returns an array with a single match if found.
db.get('my-key')
// => [ { id: 'my-key', created, updated, ... } ]
When query
is an object
it's used as filter and returns an array with the items that matched.
The value
can be any of type: string
, number
, boolean
and RegExp
.
db.get({ value: /example/ })
// => [ { id, created, updated, value: 'My example', ... }, ... ]
Without arguments a default object is created with id
, created
and updated
keys. Returns the created object.
db.set()
// => { id, created, updated }
With data
but no key
a new object is created with the default keys and the data
object. Returns the created object.
db.set({ value: 'My example' })
// => { id, created, updated, value: 'My example' }
When data
and key
are passed it does one of two things:
If the key
is found it updates that object with the data
and a new updated
value.
If no key
is found it creates a new object with the data
and all default values except id
which gets its value from key
.
Returns the updated or created object.
db.set({ value: 'My example' }, 'my-key')
// => { id: 'my-key', created, updated, value: 'My example' }
Returns either the key
that was deleted, or undefined
if no such key exists.
db.del('my-key')
// => 'my-key'