0

I have a db.json file with two objects:

  • MEMBERS
  • TEAMS

Here's the object...

{
"members": [
    {
        "id": 1,
        "firstName": "John",
        "lastName": "Doe",
        "jobTitle": "Driver",
        "team": "Formula 1 - Car 77",
        "status": "Active"
    },
    {
        "id": 2,
        "firstName": "Alex",
        "lastName": "Sainz",
        "jobTitle": "Driver",
        "team": "Formula 1 - Car 78",
        "status": "Active"
    },
    {
        "id": 3,
        "firstName": "Jeb",
        "lastName": "Jackson",
        "jobTitle": "Reserve Driver",
        "team": "Formula 1 - Car 77",
        "status": "Inactive"
    }
],
"teams": [
    {
        "id": 1,
        "teamName": "Formula 1 - Car 77"
    },
    {
        "id": 2,
        "teamName": "Formula 1 - Car 8"
    },
    {
        "id": 3,
        "teamName": "Formula 2 - Car 54"
    },
  ]
}

I will be adding a NEW member and I want to TARGET that object.

Here's my NODE JS CODE

// Submit Form!
    app.post('/api/addMember', (req, res) => {

        var isWriteable = 'is writable';
        var isNotWriteable = 'is not writable';

        console.log('REQ BODY: ', req.body);

        request('http://localhost:3000/addMember', (err, response, body) => {
            if (response.statusCode <= 500) {
                res.send(body);
                // console.log('RESPONSE!: ', response);
                // console.log('All Members BODY!: ', body);
                // console.log('REQ!: ', req);
                // Now can we Write to the file
                fs.access(dbFile, fs.constants.W_OK, (err) => {
                    console.log(`${dbFile} ${err ? isNotWriteable : isWriteable}`);

                    if (!err) {
                        fs.open(dbFile, 'wx', (err, fd) => {
                            if (err) {
                                if (err.code === 'EEXIST') {
                                    console.error('DB JSON already exists');


                                    dbFileNewMembers.push(dbFileMembers);
                                    dbFileNewTeams.push(dbFileTeams);

                                    console.log('DB FILE NEW JSON MEMBERS:', dbFileNewMembers);
                                    console.log('DB FILE NEW JSON TEAMS:', dbFileNewTeams);

//                                    saveNewMember(req.body)
//                                            .then(result => {
//
//                                                dbFileNewJSON.push(dbFileNewMembers);
//                                                dbFileNewJSON.push(dbFileNewTeams);
//
//                                                console.log('DB FILE NEW JSON:', dbFileNewJSON);
//
//                                                console.log('RESULT OF SAVE NEW MEMBER: ', result);
//                                            });



//                                    fs.appendFile(dbFile, JSON.stringify(req.body), 'utf8', (err) => {
//                                        if (err) {
//                                            console.log('ERROR in saving a member: BODY: ', err);
//                                        } else {
//
//                                            console.log('SUCCESS saving new member!', req.body);
//                                        }
//                                    });

                                    return;
                                }
                                throw err;
                            }
                        });
                    }
                });

            } else {
                console.log('ERROR! DAMN! We blew it!', err);
            }
        });
    });

I tried both functions in the commented out section.

What I get is, the new TEAM member is added at the "end" of the Object NOT at the end of the TEAMS object.

That's all I'm trying.

I did look at:

append json objects to file with nodejs

and

Add JSON objects to JSON object

but they don't address my issue.

I know I need to use appendFile() which is not an issue but I need to append to a specific object INSIDE the main JSON, in this case, TEAMS and in future cases, the team member may need to be UPDATED hence, updating the specific team member.

Thanks for any help.

UPDATE!

KG made a suggestion and I modified it.

Here are the variables:

var dbFileJSON = require('./db.json');

var obj = JSON.stringify(dbFileJSON);
console.log('DBFILE OBJ: ', obj);

console.log('DBFILE MEMBERS OBJ BEFORE PUSH: ', dbFileJSON);
dbFileJSON['members'].push(newMember);
console.log('DBFILE MEMBERS OBJ AFTER PUSH: ', dbFileJSON);

dbFileJSON = JSON.stringify(dbFileJSON);
console.log('DBFILE MEMBERS OBJ FINAL STRINGIFY: ', dbFileJSON);

dbFileJSON = JSON.parse(dbFileJSON);
console.log('DBFILE MEMBERS OBJ FINAL: ', dbFileJSON);

console.log('UPDATED TEAM members: ', dbFileJSON);

The result adds it directly to the BOTTOM of the "MEMBERS" array!

This is where I found an potential answer before I implemented KG's answer.

https://stackoverflow.com/questions/38716025/how-to-replace-old-json-object-with-a-new-one-with-nodejs

Now, the ONLY problem left is: I need to REPLACE db.json, because it's not doing that.

My final question is: How do you replace an ENTIRE JSON file with the contents of a new one because I'm still getting the original. Here's the top part of the server.js file to better help understand where I am.

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const path = require('path');
const request = require('request');
const fs = require("fs");

var hsts = require('hsts');
var xssFilter = require('x-xss-protection');
var nosniff = require('dont-sniff-mimetype');
var dbFileJSON = require('./db.json');

var dbFile = 'db.json';
var dbFileMembers = [];
var dbFileTeams = [];

const app = express();

app.use(cors());
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.raw());
app.use(bodyParser.urlencoded({ extended: true }));
app.disable('x-powered-by');
app.use(xssFilter());
app.use(nosniff());
app.set('etag', false);

app.use(helmet({
    noCache: false
}));

app.use(hsts({
    maxAge: 15552000 // 180 days in seconds
}));

app.get('/api/members', (req, res) => {
    request('http://localhost:3000/members', (err, response, body) => {
        if (response.statusCode <= 500) {
            res.send(body);
            dbFileMembers.push(body);
            console.log('BODY MEMBERS: ', body);
            console.log('BODY MEMBERS DBFILEMEMBERS: ', dbFileMembers);
            console.log('DBFILE: ', dbFileJSON);
            console.log('SUCCESS! We got the members ', dbFileMembers);
        } else {
            console.log('ERROR getting MEMBERS: ', err);
        }
    });
});

// TODO: Dropdown! DONE!
app.get('/api/teams', (req, res) => {
    request('http://localhost:3000/teams', (err, response, body) => {
        if (response.statusCode <= 500) {
            res.send(body);
            dbFileTeams.push(body);
            console.log('SUCCESS! We got the TEAMS! ', JSON.parse(dbFileTeams));
        } else {
            console.log('ERROR getting TEAMS: ', err);
        }
    });
});

Here's my code for adding a new Member

// Submit Form!
app.post('/api/addMember', (req, res) => {

    var isWriteable = 'is writable';
    var isNotWriteable = 'is not writable';

    console.log('REQ BODY: ', req.body);

    request('http://localhost:3000/addMember', (err, response, body) => {

        if (response.statusCode <= 500) {
            res.send(body);

            fs.access(dbFile, fs.constants.W_OK, (err) => {
                console.log(`${dbFile} ${err ? isNotWriteable : isWriteable}`);

                if (!err) {
                    fs.open(dbFile, 'wx', (err, fd) => {
                        if (err) {
                            console.log('FD: ', fd);
                            if (err.code === 'EEXIST') {
                                console.error('DB JSON already exists');
                                console.log('DB FILE JSON MEMBERS:', dbFileMembers);
                                console.log('DB FILE JSON TEAMS:', dbFileTeams);

                                const newMember = req.body;


                                var obj = JSON.stringify(dbFileJSON);
                                console.log('DBFILE OBJ: ', obj);

                                console.log('DBFILE MEMBERS OBJ BEFORE PUSH: ', dbFileJSON);
                                dbFileJSON['members'].push(newMember);
                                console.log('DBFILE MEMBERS OBJ AFTER PUSH: ', dbFileJSON);

                                dbFileJSON = JSON.stringify(dbFileJSON);
                                console.log('DBFILE MEMBERS OBJ FINAL STRINGIFY: ', dbFileJSON);

                                dbFileJSON = JSON.parse(dbFileJSON);
                                console.log('DBFILE MEMBERS OBJ FINAL: ', dbFileJSON);

                                console.log('UPDATED TEAM members: ', dbFileJSON);


                            }
                        }


                    });
                }
            });

        } else {
            console.log('ERROR! DAMN! We blew it!', err);
        }
    });
});

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/my-app/index.html'));
});

app.listen('8000', () => {
    console.log('Vrrroooom Vrrroooom! Server starting!');
});

That's it! Any further comment would be dandy!

2
  • Why dont you just read the file, add the object and save it? Is that an option? Commented Nov 19, 2020 at 12:31
  • Yes, I can read it but, adding to the "members" part of the object using appendFile() is the problem I'm having. I want to Add a NEW MEMBER and not at the bottom of the entire JSON object, just at the bottom of the members object. It's a good start KG. Commented Nov 19, 2020 at 19:49

1 Answer 1

1

If you dont have to use appendFile. You can try something like this.

const data = JSON.parse(fs.readFileSync('./db.json'));
data["places"] = { location: 'pta' }
fs.writeFileSync('db.json', JSON.stringify(data, null, 4));

Just note that I used blocking functions. But something along those lines.

EDIT: Looking at your code you can do this.

app.post('/api/addMember', (req, res) => {
    const filename = './db.json';

    request('http://localhost:3000/addMember', async(err, response, body) => {
        const data = await readFileJson(filename);
        data['newmemeber'] = req.body; // add to object
        await writeFileJSON(filename, JSON.stringify(data, null, 4)); // save data to file.
        res.json({ code: 1, message: 'saved to db!', data: {} })

    });
});

function readFileJson(filename) {
    return new Promise((resolve, reject) => {
        fs.readFile(filename, 'utf-8', function(err, data) {
            if (err) {
                return resolve({});
            }
            try {
                return resolve(JSON.parse(data));
            } catch (err) {
                console.log(err);
                return resolve({});
            }
        });
    });
}

function writeFileJSON(filename, data) {
    return new Promise((resolve, reject) => {
        fs.writeFile(filename, data, function(err, data) {
            if (err) {
                return reject(err);
            }
            return resolve();
        });
    });
}

Something along these lines hould work.

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

9 Comments

KG, I'm trying this... what are you replacing "Places" with and "PTA?" Just curious as I'm using MEMBERS... is PLACES = MEMBERS and PTA ===???
This is what I did from what I'm understanding you wrote and like... wish me luck! --- const newMember = req.body; dbFile['members'] = { newMember } fs.writeFileSync('db.json', JSON.stringify(dbFile, null, 4));
Sorry for the long wait, but your code, replaces the entire JSON object in db.json with the following: "db.json" which is not correct.
Hi, dont use writeFileSync or readFileSync its blocking. You will have to read the file const data = JSON.parse(fs.readFileSync('./db.json')); for example. Add a new object then save the file fs.writeFile. Check the contents before you save it. nodejs.org/api/…
Have a look at the edit. Read the docs and you will have a clear understanding.
|

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.