Languages
[Edit]
EN

Node.js - save JSON in file

0 points
Created by:
chelsea
326

In this article, we would like to show you how to save JSON in file using Node.js.

Quick solution:

const fs = require('fs');

// example JSON string
const jsonString = '{ "id": "2", "name": "Tom",  "age": "23" }';

// create JSON from the string
const jsonObject = JSON.parse(jsonString);

// stringify JSON object
const jsonData = JSON.stringify(jsonObject);

fs.writeFile('./example.txt', jsonData, (error) => {
  if (error) {
    console.error(error);
    return;
  }
});

Note:

This solution replaces the example.txt file contents if it already exists.

 

Additional arguments - flags

In this section, we present how to modify the quick solution from previous section by specifying an additional argument (flag) in fs.writeFile().

FlagDescription
r+
  • open the file for reading and writing
a
  • open the file for writing
  • positioning the stream at the end of the file
  • the file will be¬†created if it doesn't¬†exist
a+
  • open the file for reading and writing
  • positioning the stream at the end of the file
  • the file will be¬†created if it doesn't¬†exist
w+
  • open the file for reading and writing
  • positioning the stream at the beginning of the file
  • the file will be¬†created if it doesn't¬†exist

Practical example:

const fs = require('fs');

// example JSON string
const jsonString = '{ "id": "2", "name": "Tom",  "age": "23" }';

// create JSON from the string
const jsonObject = JSON.parse(jsonString);

// stringify JSON object
const jsonData = JSON.stringify(jsonObject);

fs.writeFile('./example.txt', jsonData, { flag: 'a+' }, (error) => {
  if (error) {
    console.error(error);
    return;
  }
});

Note:

Now when you run the program, the data string will be added at the end of example.txt file (but not in the separate line).

Alternative solution

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.

const fs = require('fs');

// example JSON string
const jsonString = '{ "id": "2", "name": "Tom",  "age": "23" }';

// create JSON from the string
const jsonObject = JSON.parse(jsonString);

// stringify JSON object
const jsonData = JSON.stringify(jsonObject);

try {
  const result = fs.writeFileSync('./example.txt', jsonData); // fs.writeFileSync(path, string);
} catch (error) {
  console.error(error);
}

References

Native Advertising
ūüöÄ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā

Join