1 | # outputJson(file, object, [options, callback])
|
2 |
|
3 | Almost the same as [`writeJson`](writeJson.md), except that if the directory does not exist, it's created.
|
4 |
|
5 | **Alias:** `outputJSON()`
|
6 |
|
7 | - `file` `<String>`
|
8 | - `object` `<Object>`
|
9 | - `options` `<Object>`
|
10 | - `spaces` `<Number|String>` Number of spaces to indent; or a string to use for indentation (i.e. pass `'\t'` for tab indentation). See [the docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument) for more info.
|
11 | - `EOL` `<String>` Set EOL character. Default is `\n`.
|
12 | - `replacer` [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter)
|
13 | - Also accepts [`fs.writeFile` options](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback)
|
14 | - `callback` `<Function>`
|
15 |
|
16 | ## Example:
|
17 |
|
18 | ```js
|
19 | const fs = require('fs-extra')
|
20 |
|
21 | const file = '/tmp/this/path/does/not/exist/file.json'
|
22 |
|
23 | // With a callback:
|
24 | fs.outputJson(file, {name: 'JP'}, err => {
|
25 | console.log(err) // => null
|
26 |
|
27 | fs.readJson(file, (err, data) => {
|
28 | if (err) return console.error(err)
|
29 | console.log(data.name) // => JP
|
30 | })
|
31 | })
|
32 |
|
33 | // With Promises:
|
34 | fs.outputJson(file, {name: 'JP'})
|
35 | .then(() => fs.readJson(file))
|
36 | .then(data => {
|
37 | console.log(data.name) // => JP
|
38 | })
|
39 | .catch(err => {
|
40 | console.error(err)
|
41 | })
|
42 |
|
43 | // With async/await:
|
44 | async function example (f) {
|
45 | try {
|
46 | await fs.outputJson(f, {name: 'JP'})
|
47 |
|
48 | const data = await fs.readJson(f)
|
49 |
|
50 | console.log(data.name) // => JP
|
51 | } catch (err) {
|
52 | console.error(err)
|
53 | }
|
54 | }
|
55 |
|
56 | example(file)
|
57 | ```
|