Skip to content

Local JSON Database

Susanna Nevalainen edited this page Dec 5, 2020 · 1 revision

📝 Storing data locally

This is one of the ways to store node.js app backend data. For development purposes it is possible to mocking database by storing data locally in JSON files. However this is slower and less scalable than using databases so it is not recommended approach for production environment.

You can read and write data using file system (fs) that is included in the core modules, part of node

import fs in the files you are using it

const fs = require('fs');

define paths where you want to store data

const p = path.join(
  path.dirname(process.mainModule.filename),
  'data',
  'cart.json'
);

Read data

fs.readFile(path, (err, fileContent) => {
    JSON.parse(fileContent)
}

Write data

fs.writeFile(path, JSON.stringify(cart), err => {
    console.log(err);
});

Clone this wiki locally