Using a Flat-File Database Library with Node.js
Storing data with any web service is probably important. Typically a database such as MySQL or MongoDB would be used. However both of these require database software to be installed and configured.
For some of the web applications I have been developing a “full” database is overkill for the simple data I am storing. Instead, with the nodejs-microdb it is possible to use a flat file database to store and retrieve data in a structured manner.
Including microdb with your application
In your applications package.json “dependencies” section, add the following to tell Node.js that your application depends on microdb:
"dependencies": { "nodejs-microdb": "*", }
At the top of your node application, add the following line to include the microdb library:
var microdb = require('nodejs-microdb');
Somewhere near the start of your application, add the following lines to construct a microdb object with the path to your database file:
var db = new microdb({ 'file' : data_dir_path + '/my_data.json', 'savetime' : 1 });
And that’s it: your Node.js application will now get the required library from npm and construct a new flat-file database to be used.
Storing data in the database
Store data in the database is simple. Simply call db.add(), with the data you wish to store.
The following lines will add a “username” and “password” to the database, and check that the data was added successfully:
var ident = db.add({ username: "MyUserName", password: "MyPassWord" }); if (ident === null) { console.log("An error occurred storing to DB"); }
Retrieving data from the database
The following lines will retrieve all usernames from the database, and print them to the console:
for (var item in db.data) { console.log(db.data[item].username); }
Super simple and super effective.
More information on nodejs-microdb can be found on GitHub. The tests provide some further code examples.
I have been using nodejs-microdb with my iPhone tracking web application.