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.

Interested in JavaScript? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *