single-user-db v1.1.1
Single-User-DB: A Super-Basic FS-Based Database for Single User Applications
What is this and why is this useful?
This is not a "real" database. It's just a thin wrapper around basic filesystem operations, which you might use for simplicity of setup when prototyping. Essentially, it is a script that stores and retrieves json files from a folder you specify.
Why would you use this? Sometimes it is not possible to install a proper database for whatever reason: Maybe you don't have permissions to install/symlink anything outside node on a linux server or you don't have internet and therefore need to package and copy. Also, as your data directory is just a folder of json files, this makes your data very portable. If you are prototyping for a single-user application, it might be adequate to use a "database" that is just a thin wrapper around basic filesystem operations.
While I've used test-driven development to create this module, I can't guarantee the safety of your data. You use this library at your own risk!
Required Version of Node:
- This library makes use of async/await, so you need to use a node version >= 7.6.
- If you want to set your data directory to a nested directory, you need to use a node version >= 10.12.
Usage
Setup
The data directory needs to be set upon importing. This will be the folder that will contain your data in the form of json files. The filenames in the data directory will be in the following shape: YYYYMMDD-HHMMSS-${_id}
.
const dataDirectory = "data";
const db = require("single-user-db")(dataDirectory);
Note that all calls on db
asynchronous and return promises.
Insert (new entry)
await db.insert({ _id: "explicit_id", name: "Bob", country: "UK" });
If an _id
is not explicitly passed in, this library will create a new unique _id
for you automatically.
Get (read entry)
get
requires the _id
as a parameter and simply ignores other key-value pairs. This is convenient because you can simply pass in entire objects, which you are probably already using in your program.
await db.get({ _id: "explicit_id" });
Search
If an _id
is passed in, search
defaults to get
. Otherwise it returns an array of all matches.
await db.search({ name: "Bob", country: "UK" });
Remove
For remove
only the _id is required and other key-value pairs are ignored.
await db.remove({ _id: "explicit_id" });
Update
The _id
is required. update
calls remove
and then insert
, so this will also change the timestamp of the filename. This will also remove previous data for the entry you are updating, unless you explicitly pass that information in.
await db.update({ _id: "explicit_id", name: "Bob", country: "UK" });