how to make json file for every user visits – NodeJs ExpressJ

Issue

I want to make json file for every users who visit the site. I’m using NodeJS express Js with EJS template. I don’t want to use mongoDB. I want to use json file as the db. When user visit the site and fill the form. the form data will stored in json file. Every new users who visited the site it make a new json file store the data of that specific user. Can anyone done this?. I don’t know how to use cookie and session.

Solution

If it isn’t sensible data, cookie-parser is an easy way to use cookies. Otherwise, can’t recommend enough a DBMS.

Anyways, to answer the question, other than using the fs package with writeFile, readFile and manage the object you want to use as database, there is not much more you have to do.

Here is a simple example using an array of objects as database using fs/promises package that wraps the fs methods with promises.

PS. You may want to use a better structure to avoid de O(n) complexity, like a separate file per user.
Also, concurrent access to the same file is unsafe, check the documentation of writeFile

const fs = require('fs/promises');

const fileName = 'db.json';

let data = [{
    name: 'John Doe',
    age: 42,
  },
  {
    name: 'Jane Doe',
    age: 39,
  }
];

async function main() {
  await fs.writeFile(fileName, JSON.stringify(data)); // first version of file, not really needed
  let rawData = await fs.readFile(fileName); // read file, result is still an string
  data = JSON.parse(rawData); // parse the data read to an object
  let index = data.findIndex((item) => item.name === 'John Doe'); // find index of John Doe in the array
  data[index].age = 43; // update age of John Doe
  await fs.writeFile(fileName, JSON.stringify(data)); // write back to file
  console.log(data);
}

main();

Answered By – rodrigo cordova

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published