Just a brief post: With the latest release of node.js, it is now possible to load files that only contain JSON data directly into objects using the require( [path_to_file] ) function.
Before, you had to use a function like this to achieve the same:
// a function to load json data from a file
var fs = require('fs');
function loadJSONfile (filename, encoding) {
try {
// default encoding is utf8
if (typeof (encoding) == 'undefined') encoding = 'utf8';
// read file synchroneously
var contents = fs.readFileSync(filename, encoding);
// parse contents as JSON
return JSON.parse(contents);
} catch (err) {
// an error occurred
throw err;
}
} // loadJSONfile
// this is what we needed to do now
var myData = loadJSONfile(__dirname + '/data.json');
console.log('loadJSONfile:', myData);
As of node.js 0.5.2 we can simply do the following:
// this is possible as of node.js 0.5.2
var myData = require('./data.json');
console.log('Require:', myData);
It is also noteworthy that the require statement will also cache the result of loading that JSON file, meaning that you can refer to it from many files / modules without having to process it each and every time.
In other words, this will make storing static data in files locally much, much more attractive.
Full Changelog
For the full changelog, visit the node.js blog. As of node.js 0.5.0, there also is an official Windows node.exe file, which allows Windows users to use node without running a virtual machine or build it using CygWin.
Unfortunately, however, that executable comes withoutthe Node Package Manager, meaning that you painfully have to install libraries manually. For that reason, I’m still running an older version that includes NPM.
According to Ryan Dahl’s slides at OSCOM 2011, the next major release, node.js 0.6.0 is been schedulded to arrive within four weeks. NPM, however, was not mentioned.