PointyKone
PointyKone

Reputation: 183

How to update only one key in a JSON file with node.js

I am making an API for my minecraft server and have been able to get as far as getting the JSON file to update what I send it in a POST request. I would like to know if it is possible to only update on key of the JSON file.

This is my current code:

var fs = require('fs');
var fileName = './serverStatus.json';
var file = require(fileName);
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

const cors = require('cors');
const { fileURLToPath } = require('url');

app.get('/status', alldata);
function alldata(request, response) {
    response.send(file);
}

app.post('/status', (req, res) => {
    if (!req.is('application/json')) {
        res.status(500);
        res.send('500 - Server Error');
    } else {
        res.status(201);
        fs.writeFile(
            fileName,
            JSON.stringify(req.body, null, 4),
            function writeJSON(err) {
                if (err) return console.error(err);
                console.log(JSON.stringify(file));
                console.log('writing to ' + fileName);
            }
        );
        res.send(file);
    }
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () =>
    console.log(`Server running on: http://localhost:${PORT}`)
);

and my JSON file:

{
    "lobby": "offline",
    "survival": "offline",
    "creative": "offline"
}

Thanks in advance!

Upvotes: 1

Views: 7254

Answers (2)

Jack Yu
Jack Yu

Reputation: 2425

You could use fs.readFileSync or to read file content.
Then update your JSON content such as jsonData["survival"] = "online".
Final, write content back to file with fs.writeFile. (See note-1)
You could see the following example code.

const fs = require("fs");

// 1. get the json data
// This is string data
const fileData = fs.readFileSync("./serverStatus.json", "utf8")
// Use JSON.parse to convert string to JSON Object
const jsonData = JSON.parse(fileData)

// 2. update the value of one key
jsonData["survival"] = "online"

// 3. write it back to your json file
fs.writeFile("./serverStatus.json", JSON.stringify(jsonData))

Note-1: Because you save data in file, you need to write the whole data when you want to update file content.

But, if you want to get the latest file content after you write your new data into file, you should fs.readFileSync your file again like following code to avoiding any modified which are forgot to save.

app.get('/status', alldata);
function alldata(request, response) {
    const fileContent = fs.readFileSync(fileName, "utf8");
    const fileJsonContent = JSON.parse(fileContent)
    // do other stuff
    response.send(fileContent);
}

Upvotes: 3

bob
bob

Reputation: 7985

var fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');

var fileName = './serverStatus.json';

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// maybe use this instead of bodyParser:
//app.use(express.json());

const cors = require('cors');
const { fileURLToPath } = require('url');

app.get('/status', alldata);
function alldata(request, response) {
    response.send(file);
}

app.post('/status', (req, res) => {
    if (!req.is('application/json')) {
        res.status(500);
        res.send('500 - Server Error');
    } else {

        // read full config file:
        var src = fs.readFileSync(fileName);

        // convert src json text to js object
        var srcObj = JSON.parse(src);

        // convert req json text to js object
        var reqObj = JSON.parse(req.body);

        // update the src with the new stuff in the req
        for(var prop in reqObj){
            srcObj[prop] = reqObj[prop];
        }

        // update any additional things you want to do manually like this
        srcObj.bob = "creep";

        // convert the updated src object back to JSON text
        var updatedJson = JSON.stringify(srcObj, null, 4);

        // write the updated src back down to the file system
        fs.writeFile(
            fileName,
            updatedJson,
            function (err) {
                if (err) {
                    return console.error(err);
                }
                console.log(updatedJson);
                console.log('updated ' + fileName);
            }
        );

        res.send(updatedJson);
    }
});

const PORT = process.env.PORT || 3000;

app.listen(PORT, () =>
    console.log(`Server running on: http://localhost:${PORT}`)
);

//res.status(201);

Upvotes: 1

Related Questions