jsonfile
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
graceful-fs | 4.2.11 | 9.57 kB | ISC | prod optional | |
universalify | 2.0.1 | 2.02 kB | MIT | prod |
Jsonfile is a lightweight, non-browser compatible Node.js module that simplifies the operations of reading and writing JSON files. It eliminates the need to manually write JSON.stringify() and fs.writeFile(), or JSON.parse() with fs.readFile() enclosed in try/catch blocks, drastically increasing coding efficiency.
To harness jsonfile in your project, first, install the module by using npm install command as below:
npm install --save jsonfile
Using jsonfile is quite straightforward. Here are several common use-case code snippets:
Reading a JSON file asynchronously
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
jsonfile.readFile(file, function (err, obj) {
if (err) console.error(err)
console.dir(obj)
})
Writing to a JSON file asynchronously
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj, function (err) {
if (err) console.error(err)
})
What's compelling about jsonfile is that it supports both callback style and promise style. So, if you prefer using promises, you can rewrite the reading and writing operations like this:
Reading a JSON file with promises
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
jsonfile.readFile(file)
.then(obj => console.dir(obj))
.catch(error => console.error(error))
Writing to a JSON file with promises
const jsonfile = require('jsonfile')
const file = '/tmp/data.json'
const obj = { name: 'JP' }
jsonfile.writeFile(file, obj)
.then(res => {
console.log('Write complete')
})
.catch(error => console.error(error))
The jsonfile documentation can be found in the readme file on the jsonfile GitHub repository. The readme file provides a comprehensive guide on how to use the module, showing various examples and explaining the parameters for each function. The repository's url is: git+ssh://git@github.com/jprichardson/node-jsonfile.git