Monday, February 3, 2014

Object Persistence in NodeJS

pst-obj is a rudimentary utility for setting up a persistence layer in your app for node. It extends an object with a single non-enumerable function that allows you to persist that object to a specified file location. When stored the object is serialized to JSON format and stored in a UTF-8 character encoded file.

Install

npm install pst-obj

Download

You can download it here or peruse the code on github: https://github.com/patcullen/pst-obj.

Why

Quite often now I'm finding myself creating little doodads in nodejs. My latest invention [read distraction] was a small app to control the light overhead in the room via a relay. It had some automatic triggers defined to flip once text had been detected in certain RSS streams, and of course a small one page one button interface to change the state of the light (mostly to play disco-tech in the office).

It's these low volume low risk types of applications I don't really want to setup a database or any third party services for. I had considered settings file type interfaces, but really much preferred the idea of JSON. (I also wanted half a good reason to publish to npm for a first time.) I've used pst-obj to persist single attribute objects, and some with fairly large (long and deep) data structures - the general rule is, if you know your data can be JSON'ed, then this should suffice as a usable, albeit rudimentary, persistence option.

Example

// Start ye'r engines
var
http = require('http'),
persist = require('pst-obj'),
state = { hits: 0 }
;
// api/layer to interface with state object
function getPageCount() {
state.hits++;
state.persist();
return state.hits;
}
// initialize state object
persist.get('state.json', state, function(data, err) {
state = data;
console.log('Stored state ' + (err ? 'created' : 'fetched') + ', number of site hits: ' + state.hits);
});
// Create an HTTP server
var app = http.createServer(function (req, res) {
if (req.url == '/') {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h2>Welcome to a test</h2><p>This page has been loaded ' + getPageCount() + ' times.</p>');
} else {
res.end();
}
});
// served
app.listen(8081);
console.log('Listening on http://0.0.0.0:8081');
view raw example.js hosted with ❤ by GitHub

The above example when started and stopped a few times while also refreshing the page in a browser, should give a result similar to this:

In the Console

In the Browser

No comments: