A desktop web-app with node-webkit, database with nedb !

2014-01-21 Last modified on 2021-05-24

Why ?

In my secret project to conquer the world, I want to store stuff.

This is an update after this article

The release is available here.

The database

I am using NeDB, a NoSQL database for nodeJS.

To install it, just use npm install nedb.

The test page

We're adding a page with a form to add dudes

The dude

(image from imdb)

The new page looks like this:

DB test app

The page contains:

  • a form
  • a list of dudes

Le code

The database: creating or loading

Very hard:

var Datastore = require('nedb');
var db = new Datastore({
  filename : getUserDataPath() + '/dudes.db',
  autoload: true
});

The getUserDataPath() function returns the .exe directory:

function getUserDataPath() {
    var path = require('path');
    return path.dirname(process.execPath);
}

Saving user

Very hard again: db.insert, with the data to insert, and a callback:

function saveUser(firstName, lastName) {
  db.insert({
    firstName: firstName,
    lastName: lastName
  }, function(err, newDoc) {
    if (err) {
      console.log(err);
    } else {
      showUser(newDoc);
    }
  });
}

Retrieving all the users

A db.find, with an empty object {} retrieves all the users. We can add things to filter the results (see here):

function getAllTheThings() {
  db.find({}, function(err, docs) {
    for (var i = 0; i < docs.length; i++) {
      showUser(docs[i]);
    }
  });
}

Other functions in the script.js are here for displaying stuff and are not the subject of this post.

Conclusion

Epic win ! We can use a Node.js database to save stuff !

Just one thing: node-webkit actually executes the html in a temporary directory (calling process.cwd() shows the folder).