UNPKG

1.63 kBMarkdownView Raw
1# readJson(file, [options, callback])
2
3Reads a JSON file and then parses it into an object. `options` are the same
4that you'd pass to [`jsonFile.readFile`](https://github.com/jprichardson/node-jsonfile#readfilefilename-options-callback).
5
6**Alias:** `readJSON()`
7
8- `file` `<String>`
9- `options` `<Object>`
10- `callback` `<Function>`
11
12## Example:
13
14```js
15const fs = require('fs-extra')
16
17// With a callback:
18fs.readJson('./package.json', (err, packageObj) => {
19 if (err) console.error(err)
20
21 console.log(packageObj.version) // => 0.1.3
22})
23
24// With Promises:
25fs.readJson('./package.json')
26.then(packageObj => {
27 console.log(packageObj.version) // => 0.1.3
28})
29.catch(err => {
30 console.error(err)
31})
32
33// With async/await:
34async function example () {
35 try {
36 const packageObj = await fs.readJson('./package.json')
37
38 console.log(packageObj.version) // => 0.1.3
39 } catch (err) {
40 console.error(err)
41 }
42}
43
44example()
45```
46
47---
48
49`readJson()` can take a `throws` option set to `false` and it won't throw if the JSON is invalid. Example:
50
51```js
52const fs = require('fs-extra')
53
54const file = '/tmp/some-invalid.json'
55const data = '{not valid JSON'
56fs.writeFileSync(file, data)
57
58// With a callback:
59fs.readJson(file, { throws: false }, (err, obj) => {
60 if (err) console.error(err)
61
62 console.log(obj) // => null
63})
64
65// Wtih Promises:
66fs.readJson(file, { throws: false })
67.then(obj => {
68 console.log(obj) // => null
69})
70.catch(err => {
71 console.error(err) // Not called
72})
73
74// With async/await:
75async function example (f) {
76 const obj = await fs.readJson(f, { throws: false })
77
78 console.log(obj) // => null
79}
80
81example(file)
82```