build status

Node.js - jsonfile

Easily read/write JSON files.

Why?

Writing JSON.stringify() and then fs.writeFile() and JSON.parse() with fs.readFile() enclosed in try/catch blocks became annoying.

Installation

  1. npm install jsonfile --save

API

readFile(filename, [options], callback)

  1. var jf = require('jsonfile')
  2. , util = require('util');
  3. var file = '/tmp/data.json';
  4. js.readFile(file, function(err, obj) {
  5. console.log(util.inspect(obj));
  6. });

readFileSync(filename, [options])

  1. var jf = require('jsonfile')
  2. , util = require('util');
  3. var file = '/tmp/data.json';
  4. console.log(util.inspect(jf.readFileSync(file)));

writeFile(filename, [options], callback)

  1. var jf = require('jsonfile')
  2. var file = '/tmp/data.json';
  3. var obj = {name: 'JP'};
  4. jf.writeFile(file, obj, function(err) {
  5. console.log(err);
  6. })

writeFileSync(filename, [options])

  1. var jf = require('jsonfile')
  2. var file = '/tmp/data.json';
  3. var obj = {name: 'JP'};
  4. jf.writeFileSync(file, obj);

spaces

Number of spaces to indent JSON files.

default: 2

  1. var jf = require('jsonfile');
  2. jf.spaces = 4;
  3. var file = '/tmp/data.json';
  4. var obj = {name: 'JP'};
  5. jf.writeFile(file, obj, function(err) { //json file has four space indenting now
  6. console.log(err);
  7. });

Contributions

If you contribute to this library, please don’t change the version numbers in your pull request.

Contributors

(You can add your name, or I’ll add it if you forget)

License

(MIT License)

Copyright 2012-2013, JP Richardson jprichardson@gmail.com