Skip to content

Commit

Permalink
document 'json' option
Browse files Browse the repository at this point in the history
  • Loading branch information
pkrumins committed Sep 15, 2010
1 parent abc92a6 commit f212285
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions readme.txt
Expand Up @@ -21,27 +21,38 @@ It provides .set and .get methods that are also continuations,
Store('users.db', function (err, db) {
db.set('pkrumins', 'cool dude', function (error) {
// value 'pkrumins' is now set to 'cool dude'
db.get('pkrumins', function (error, value) {
db.get('pkrumins', function (error, value, key) {
console.log(value); // cool dude
});
});
});

If you wish to store JSON objects in the database, you may pass a dict with the
key 'json' set to true and the key 'filename' for file as the first argument to
Store,

Store({ filename : 'objects.db', json : true },
function (error, db) {
// now any .set and .get operations will call JSON.stringify
// and JSON.parse on values.
}
);

It also has .filter function that takes a predicate, callback and done function.
The .filter function calls callback on each row for which predicate is true.
After it's done filtering, it calls done function.

Here is an example:

Store('users.db', function (err, db) {
Store({ filename : 'users.db', json : true }, function (err, db) {
var users = [];
db.filter(
function (user, userInfo) { //1//
return JSON.parse(userInfo).age < 20
return userInfo.age < 20
},
function (err, user, userInfo) { //2//
if (err) throw err;
users.push(JSON.parse(userInfo));
users.push(userInfo);
},
function () { //3//
console.log("Users younger than 20:");
Expand All @@ -52,8 +63,6 @@ Here is an example:
);
});

In this example it's assumed that users are stored in the database as JSON objects.
The keys are usernames and values are JSON objects.
The filter function here takes the predicate function //1//, parses each record and
returns true if user's age is less than 20.
Now if the age is less than 20, filter calls callback function //2//, which adds each
Expand All @@ -63,11 +72,11 @@ prints out all usernames of youngters.

Store also has .forEach method that iterates over all of its values,

Store('users.db', function (db) {
Store({ filename: 'users.db', json : true }, function (db) {
db.forEach(
function (err, key, val) {
if (err) throw err;
console.log("User " + key + " is " + JSON.parse(val).age + " old.");
console.log("User " + key + " is " + val.age + " old.");
},
function () {
console.log("Done with all users.");
Expand Down

0 comments on commit f212285

Please sign in to comment.