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 ?