Using Loki.js in Node scripts

Loki.js is a filesystem based database (like Sqllite), but that serializes to Javascript.

To create an empty database in Node, you can do the following – this creates an empty database.

const loki = require("lokijs");
const db = new loki("db.json");
db.save();

Once you have a database, you can import existing files into it. If you want to do this without erasing the database each time, you have to check if the data collection exists each time.

const fs = require("fs");
const files = fs.readdirSync("1/");

const talks = db.addCollection("talks");
function loadCollection(colName, callback) {
  db.loadDatabase({}, () => {
    let existingCollection = db.getCollection(colName);

    if (!existingCollection) {
      existingCollection = db.addCollection("talks");
    }

    callback(existingCollection);
  });
}

loadCollection("talks", (talks) => {
  const allFiles = fs.readdirSync("./1");

  for (let i in allFiles) {
    let filename = "1/" + files[i];
    const talk = JSON.parse(fs.readFileSync(filename));
    talks.insert(talk);
  }      
 
  db.saveDatabase();
});

Once you do this, you’ll have a massive JSON file to work with further.