Thursday, 8 June 2017

Making an entry in a JSON file locally using ExpressJS without jsonfile module

I want to create an entry of an object in a locally stored JSON file through ExpressJS without using jsonfile npm module. Need some help here. The function is to be written in the commented area.

var express=require('express');
var app=express();
var cookieParser=require('cookie-parser');
var bodyParser=require('body-parser');

app.use(bodyParser.json({limit:'10mb',extended:true}));
app.use(bodyParser.urlencoded({limit:'10mb',extended:true}));
var users=require('./users.json');

var myArray=[];

app.get('/mydata',function(req,res){
        res.send(myArray);
});

app.post('/mydata/create',function(req,res){
        console.log(req.body);
        myArray.push(req.body.value);
        res.send(myArray);
});

app.put('/mydata/createjson',function(req,res,val){
        //function to be written here
})

app.put('/mydata/:value/edit',function(req,res){

});

app.get('/users',function(req,res){
        res.send(users);
});

app.listen(4000,function(){
        console.log('listening on 4000');

});

This is users.json

[{
    "mobileNumber": 1234567890,
    "email": "newmail@gmail.com",
    "lastName": "Watson",
    "firstName": "George",
    "userName": "GeorgeWatson1"
},
{
    "mobileNumber": 0987654321,
    "email": "abc@xyz.com",
    "lastName": "Banks",
    "firstName": "John",
    "userName": "JohnBanks1"
}
]

Suppose this is to be entered

[
{
    "mobileNumber": 0987654321,
    "email": "jhg@xyz.com",
    "lastName": "abc",
    "firstName": "xyz",
    "userName": "xyzabc1"
}
]



via Anurag Sharma

No comments:

Post a Comment