1

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!

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

7 Comments

So if I want to only update one key, then I would have to put the JSON in the actual javascript file? Or do you think that making seperate files for all of the servers would be easier?
I wrote an example in my updated answer. It depend on the situations. If multiple request is coming to modify server status at the same time, It might cause some problem. Both request will read file first. We assume first request want survival online, second request want creative online. But, they get the status all offline in first action which read file. The second request might cover the first request modification. The last content in file might be {"lobby": "offline","survival": "offline","creative": "online"}. survival will not be online status.
So, I think it's good for separating server file.
Ok, thank you so much. Is there a way to only edit on file depending on the POST request key?
You might put request body like {"survival" :true} in POST request. After your express receive the, you could access the value by req.body.survival. Then you could use jsonData["survival"] = req.body.survival to assign the value.
|
1
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);

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.