Akercode.com

Node.js In-Memory Database

An in-memory database (IMDB) is a database that is stored in the computer's main memory, RAM (Random Access Memory), which is theoretically faster than a hard drive because they require fewer CPU instructions and the data travels much shorter than from a disk.

Since the Node.js In-memory database is not persistent, meaning it will be wiped out between sessions and application re-starts, it can be useful for prototyping, or when writing tests that should not interfere with the main database.

If you're looking for the best JavaScript database for this use case, you may want to look at the most popular and consistently updated, and here are two of them.

Prerequisites

sqlite3 in-memory example

The sqlite3 module for Node.js has an in-memory function that utilizes read & writing data to RAM, where every session is a separate in-memory database.

const sqlite3 = require('sqlite3').verbose();

// const db = new sqlite3.Database('./movies.db');  // Read from file on disk
const db = new sqlite3.Database(':memory:');        // Read from in-memory

A better example could be a Node.js express app, where a movies table is created on application start, and filled with 3 great movies. When making a request to the /movies endpoint you should get a list of the movies, directly from your RAM.

const express = require('express')
const app = express()
const port = 3002

const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database(':memory:');

app.use(express.json())                         // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

// Create table and insert data on application start
db.serialize(() => {
  db.run("CREATE TABLE movies (title TEXT)");

  var stmt = db.prepare("INSERT INTO movies VALUES (?)");
  stmt.run("Harry Potter and the Prisoner of Azkaban");
  stmt.run("GoldenEye");
  stmt.run("Happy Gilmore");
  stmt.finalize();
});

// Get all movies
app.get('/movies', (req, res) => {
  db.serialize(() => {
    db.all(`SELECT rowid AS id,
                    title
            FROM movies`, (err, rows) => {
      res.send(JSON.stringify(rows));
    });
  });
})

app.listen(port, () => {
  console.log(`Listening on port ${port}.`)
})

When stopping the application, the database with all its data is then gone.

lokijs in-memory example

Another example with the popular npm package lokijs which is an in-memory document oriented database:

Its goal is to store javascript objects as documents in a noSQL manner and retrieve them using a similar approach.

In-memory NoSQL is mentioned as one of the main features in the Github repository.

const express = require('express')
const app = express()
const port = 3002

var loki = require('lokijs')
var db = new loki('example.db');

app.use(express.json())                         // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

// Create table and insert data on application start
var movies = db.addCollection('movies');
movies.insert( { title : 'Harry Potter and the Prisoner of Azkaban' } );
movies.insert( { title : 'GoldenEye' } );
movies.insert( { title : 'Happy Gilmore' } );

// Get all movies
app.get('/movies', (req, res) => {
    var results = movies.find();
    res.send(results);
})

app.listen(port, () => {
  console.log(`Listening on port ${port}.`)
})

These are just two of many libraries that utilize in-memory databases for Node.js.

Conclusion

In-memory storage for your Node js database can be a useful solution when performance is key. By using local storage, you eliminate the need for a database server.

To find the best in memory database solutions for your use case, look at the most widely used and regularly updated ones, and most importantly, familiarize yourself by experimenting.