EN
Node.js - save JSON in file
0 points
In this article, we would like to show you how to save JSON in file using Node.js.
Quick solution:
xxxxxxxxxx
1
const fs = require('fs');
2
3
// example JSON string
4
const jsonString = '{ "id": "2", "name": "Tom", "age": "23" }';
5
6
// create JSON from the string
7
const jsonObject = JSON.parse(jsonString);
8
9
// stringify JSON object
10
const jsonData = JSON.stringify(jsonObject);
11
12
fs.writeFile('./example.txt', jsonData, (error) => {
13
if (error) {
14
console.error(error);
15
return;
16
}
17
});
Note:
This solution replaces the
example.txt
file contents if it already exists.
In this section, we present how to modify the quick solution from previous section by specifying an additional argument (flag) in fs.writeFile()
.
Flag | Description |
---|---|
r+ |
|
a |
|
a+ |
|
w+ |
|
Practical example:
xxxxxxxxxx
1
const fs = require('fs');
2
3
// example JSON string
4
const jsonString = '{ "id": "2", "name": "Tom", "age": "23" }';
5
6
// create JSON from the string
7
const jsonObject = JSON.parse(jsonString);
8
9
// stringify JSON object
10
const jsonData = JSON.stringify(jsonObject);
11
12
fs.writeFile('./example.txt', jsonData, { flag: 'a+' }, (error) => {
13
if (error) {
14
console.error(error);
15
return;
16
}
17
});
Note:
Now when you run the program, the
data
string will be added at the end ofexample.txt
file (but not in the separate line).
In this example, we use fs.writeFileSync()
as an alternative solution to fs.writeFile()
. The API also replaces the contents of the file if it does already exist.
xxxxxxxxxx
1
const fs = require('fs');
2
3
// example JSON string
4
const jsonString = '{ "id": "2", "name": "Tom", "age": "23" }';
5
6
// create JSON from the string
7
const jsonObject = JSON.parse(jsonString);
8
9
// stringify JSON object
10
const jsonData = JSON.stringify(jsonObject);
11
12
try {
13
const result = fs.writeFileSync('./example.txt', jsonData); // fs.writeFileSync(path, string);
14
} catch (error) {
15
console.error(error);
16
}