1

I am trying to add new JSON object to an array which is present in an external file. I am unable to figure out how to do that.

I use push method which is only updating array ,but changes are not being reflected in external file.

index.js

const expres=require('express');
const exphnd=require('express-handlebars');
const students=require('./students_data');
const fs=require('fs');
const uuid=require('uuid');

app=expres();
const port=5000;

app.engine('handlebars', exphnd({defaultLayout:'main'}));
app.set('view engine', 'handlebars');

app.use(expres.json());
app.use(expres.urlencoded({extended:false}));

app.get('/welcome',(req,res) => {
    res.render('welcome');
});

app.get('/register',(req,res) => {
    res.render('register');
});

app.post('/register',(req,res) => {

    var name_reg = /^[A-Za-z]+$/;
    var rol_reg= /^[0-9]*$/;
    var marks_reg = /^[0-9]*$/; 
    if(req.body.name.match(name_reg) && (req.body.std ==='SE'|| req.body.std ==='TE' || req.body.std ==='BE') && req.body.rollno.match(rol_reg) && req.body.marks.match(marks_reg))
    {          
          var newstud={
            id:uuid.v4(),
            name:req.body.name,
            std:req.body.std,
            rol_no:req.body.rollno,
            marks:req.body.marks
          };     
          students.push(newstud);
          res.json(students);
    }
    else{
        res.status(400).json({msg:'some data is wrong'});
    }
});

app.get('/dashboard',(req,res) =>{
    res.render('dashboard',{stud_arr:students});
    console.log(students);
});
           
//create a server on port 5000
app.listen(5000,(req,res) => {
    console.log('server is listening');
})

external file in which array is present

var students=[
    {
        id:1,
        name:"bhagyashri",
        std:"TE",
        rol_no:45,
        marks:66
    },
    {
        id:2,
        name:"zxc",
        std:"SE",
        rol_no:57,
        marks:76
    },
    {
        id:3,
        name:"qwe",
        std:"SE",
        rol_no:57,
        marks:76
    }
];

module.exports=students;

output after registering new student

server is listening
    [
      { id: 1, name: 'bhagyashri', std: 'TE', rol_no: 45, marks: 66 },
      { id: 2, name: 'zxc', std: 'SE', rol_no: 57, marks: 76 },
      { id: 3, name: 'qwe', std: 'SE', rol_no: 57, marks: 76 },
      {
        id: '37776edf-9e0d-435c-a976-79b270d3bcc1',
        name: 'purva',
        std: 'TE',
        rol_no: '34',
        marks: '78'
      }
    ]

but, new record with id 37776edf-9e0d-435c-a976-79b270d3bcc1 is not added to students.js.

can anyone please tell me how to add that ?

5
  • Since you're model's data is static, I think the only option is to dynamically re-write the model file with the updated students array. Commented Jan 12, 2021 at 9:32
  • but i won't able to rewrite module.exports=students; and var student everytime i rewrite.please tell me how to do that Commented Jan 13, 2021 at 6:42
  • Exactly. This is why developers use a database. If you're not willing to use a database, you can use a datafiles approach. Have a csv-file with the data, and in "./students_data" simply open the file and read it, organise it as a JS object and export it. the same goes for updating it. Commented Jan 13, 2021 at 6:53
  • insted i will use mongoDB Commented Jan 13, 2021 at 11:54
  • Great, good luck :) Commented Jan 13, 2021 at 12:28

2 Answers 2

1

You didn't save data into the file. So the new record will never appears in the file.

I suggest you use fs.readFileSync() method instead of requre() function to load the file which you stored data. And keep data in pure JSON format just like this:

students_data.json

[
  {
    "id": 1,
    "name": "bhagyashri",
    "std": "TE",
    "rol_no": 45,
    "marks": 66
  },
  {
    "id": 2,
    "name": "zxc",
    "std": "SE",
    "rol_no": 57,
    "marks": 76
  },
  {
    "id": 3,
    "name": "qwe",
    "std": "SE",
    "rol_no": 57,
    "marks": 76
  }
]

Because fs.readFileSync() method load file as text, so it is necessary to use JSON.parse() method to convert JSON text into javascript objects. Use JSON.stringify() method to convert javascript objects into JSON text and call fs.writeFileSync() method to save data into file.

Code like this:

// load and parse data
var students = JSON.parse(fs.readFileSync('./students_data.json'));

// your codes

var newstud = {
  // all the property
}
students.push(newstud);
// stringify and save data to file
fs.writeFileSync('./students_data.json', JSON.stringify(students));

Relative paths which passed in fs.readFileSync() will be resolved relative to the current working directory as determined by calling process.cwd(). It is different to require()

One more thing, it is better to use database store data if you read and write data frequently

Sign up to request clarification or add additional context in comments.

Comments

0

You load data from your file const students = require('./students_data') but your array is not linked to your file. Updating student will not magically update your file, you have to re-write it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.