-1

I am a beginner. I'd like to push data to JSON array file.

In this case, I want to push this:

{
    "name" : "name1",
    "pass" : "password1"
    
},

This is index.js:

var express = require('express');
var fs = require('fs'); // util to read file
var app = express();

app.get('/',function(req,res){
        //code here
})

And this is data.json

[
  
    //pushed data here    
  
]
Toma Rodin
  • 13
  • 4

2 Answers2

0

Read file:

var fs = require('fs');
var array = JSON.parse(fs.readFileSync('data.json', 'utf8'));

Push data:

array.push({
    "name" : "name1",
    "pass" : "password1"
})

Overwrite file:

var jsonArray = JSON.stringify(array)
fs.writeFileSync(path,jsonArray,{encoding:'utf8',flag:'w'})
0

This is a rough idea of what you are asking for . What this chunk is doing is reading the data.json then Copying it to a new array where we can push/mutate data then re-writes the data.json with updatations

var express = require('express');
var fs = require('fs'); // util to read file
var app = express();


app.get('/file', (req,res)=>{
        fs.readFile('./data.json', 'utf-8',(err,data)=>{
        data2 = JSON.parse(data);
        dataNew = [...data2];
        dataToPush = {"pass": "password"};
        dataNew.push(dataToPush)
        fs.writeFileSync('data.json', JSON.stringify(dataNew))
      })
      res.end();
    }

This is data.json

 [
  //pushed data will come here
 ]

Try running this code first yourself to get a better idea then you can easily implement it .