1 | # writeJson(file, object, [options, callback])
|
2 |
|
3 | Writes an object to a JSON file.
|
4 |
|
5 | **Alias:** `writeJSON()`
|
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 | // With a callback:
|
22 | fs.writeJson('./package.json', {name: 'fs-extra'}, err => {
|
23 | if (err) return console.error(err)
|
24 |
|
25 | console.log('success!')
|
26 | })
|
27 |
|
28 | // With Promises:
|
29 | fs.writeJson('./package.json', {name: 'fs-extra'})
|
30 | .then(() => {
|
31 | console.log('success!')
|
32 | })
|
33 | .catch(err => {
|
34 | console.error(err)
|
35 | })
|
36 |
|
37 | // With async/await:
|
38 | async function example () {
|
39 | try {
|
40 | await fs.writeJson('./package.json', {name: 'fs-extra'})
|
41 | console.log('success!')
|
42 | } catch (err) {
|
43 | console.error(err)
|
44 | }
|
45 | }
|
46 |
|
47 | example()
|
48 | ```
|
49 |
|
50 | ---
|
51 |
|
52 | **See also:** [`outputJson()`](outputJson.md)
|