readJson(file[, options][, callback])
读取JSON文件,然后将其解析为对象。
Alias: readJSON()
file
<String>
options
<Object>
(与 [jsonFile.readFile()](https://github.com/jprichardson/node-jsonfile#readfilefilename-options-callback)
options一样)
callback
<Function>
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| const fs = require('fs-extra')
fs.readJson('./package.json', (err, packageObj) => { if (err) console.error(err) console.log(packageObj.version) })
fs.readJson('./package.json') .then(packageObj => { console.log(packageObj.version) }) .catch(err => { console.error(err) })
async function example () { try { const packageObj = await fs.readJson('./package.json') console.log(packageObj.version) } catch (err) { console.error(err) } }
example()
|
readJson()可以接受设置为false的throws选项,如果JSON无效,则不会抛出。
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| const fs = require('fs-extra')
const file = '/tmp/some-invalid.json' const data = '{not valid JSON' fs.writeFileSync(file, data)
fs.readJson(file, { throws: false }, (err, obj) => { if (err) console.error(err) console.log(obj) })
fs.readJson(file, { throws: false }) .then(obj => { console.log(obj) }) .catch(err => { console.error(err) })
async function example (f) { const obj = await fs.readJson(f, { throws: false }) console.log(obj) }
example(file)
|