Using JSON as a Database in Node.js: A Guide to Reading and Writing

Posted by

How To Read & Write JSON in Node.js

How To Read & Write JSON in Node.js

Node.js is a popular JavaScript runtime that allows you to build server-side applications. One common use case for Node.js is to read and write JSON data. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write. In this article, we will discuss how to read and write JSON in Node.js and use JSON as a database.

Reading JSON in Node.js

Node.js provides a built-in module called fs (file system) that allows you to read and write files. To read JSON data from a file, you can use the fs.readFile method. Here’s an example of how to read JSON data from a file:

    
      const fs = require('fs');

      fs.readFile('data.json', 'utf8', (err, data) => {
        if (err) {
          console.error(err);
          return;
        }
        const jsonData = JSON.parse(data);
        console.log(jsonData);
      });
    
  

Writing JSON in Node.js

To write JSON data to a file in Node.js, you can use the fs.writeFile method. Here’s an example of how to write JSON data to a file:

    
      const fs = require('fs');

      const jsonData = { name: 'John Doe', age: 30, email: 'john@example.com' };

      fs.writeFile('data.json', JSON.stringify(jsonData), 'utf8', (err) => {
        if (err) {
          console.error(err);
          return;
        }
        console.log('Data has been written to data.json');
      });
    
  

Using JSON as a Database

In Node.js, you can use JSON as a simple database for storing and retrieving data. You can read and write JSON data to a file as shown above, and use that file to store and retrieve data for your application. While JSON is not a full-fledged database like MongoDB or MySQL, it can be a good choice for small applications or prototyping.

Conclusion

In this article, we have discussed how to read and write JSON in Node.js. We have also explored how to use JSON as a simple database for storing and retrieving data. JSON is a versatile and lightweight data-formatting option that can be useful in a variety of applications. With Node.js, you can easily read and write JSON data and use it as a database for your applications.