githubEdit

Node.js - jsonfile

Easily read/write JSON files in Node.js. Note: this module cannot be used in the browser.

npm Packagearrow-up-right build statusarrow-up-right windows Build statusarrow-up-right

Standard JavaScriptarrow-up-right

Why?

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

Installation

npm install --save jsonfile

API


readFile(filename, [options], callback)

options (object, default undefined): Pass in any fs.readFilearrow-up-right options or set reviver for a JSON reviverarrow-up-right.

  • throws (boolean, default: true). If JSON.parse throws an error, pass this error to the callback. If false, returns null for the object.

You can also use this method with promises. The readFile method will return a promise if you do not pass a callback function.


readFileSync(filename, [options])

options (object, default undefined): Pass in any fs.readFileSyncarrow-up-right options or set reviver for a JSON reviverarrow-up-right.

  • throws (boolean, default: true). If an error is encountered reading or parsing the file, throw the error. If false, returns null for the object.


writeFile(filename, obj, [options], callback)

options: Pass in any fs.writeFilearrow-up-right options or set replacer for a JSON replacerarrow-up-right. Can also pass in spaces, or override EOL string or set finalEOL flag as false to not save the file with EOL at the end.

Or use with promises as follows:

formatting with spaces:

overriding EOL:

disabling the EOL at the end of file:

appending to an existing JSON file:

You can use fs.writeFile option { flag: 'a' } to achieve this.


writeFileSync(filename, obj, [options])

options: Pass in any fs.writeFileSyncarrow-up-right options or set replacer for a JSON replacerarrow-up-right. Can also pass in spaces, or override EOL string or set finalEOL flag as false to not save the file with EOL at the end.

formatting with spaces:

overriding EOL:

disabling the EOL at the end of file:

appending to an existing JSON file:

You can use fs.writeFileSync option { flag: 'a' } to achieve this.

License

(MIT License)

Copyright 2012-2016, JP Richardson [email protected]envelope

Last updated