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.

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:

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.