【问题标题】:How to update only one key in a JSON file with node.js如何使用 node.js 仅更新 JSON 文件中的一个键
【发布时间】:2021-03-30 08:27:15
【问题描述】:

我正在为我的 minecraft 服务器创建一个 API,并且能够获取 JSON 文件以更新我在 POST 请求中发送的内容。我想知道是否可以只更新 JSON 文件的键。

这是我当前的代码:

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}`)
);

还有我的 JSON 文件:

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

提前致谢!

【问题讨论】:

    标签: node.js json express


    【解决方案1】:

    您可以使用fs.readFileSync 或读取文件内容。
    然后更新您的 JSON 内容,例如 jsonData["survival"] = "online"
    最后,使用fs.writeFile 将内容写回文件。 (见注 1)
    您可以看到以下示例代码。

    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))
    

    注意一:因为你是把数据保存在文件里,所以要更新文件内容时需要写whole data

    但是,如果您想在将新数据写入文件后获取最新的文件内容,您应该再次fs.readFileSync您的文件,如以下代码以避免任何忘记保存的修改.

    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);
    }
    

    【讨论】:

    • 所以如果我只想更新一个键,那么我是否必须将 JSON 放入实际的 javascript 文件中?还是您认为为所有服务器制作单独的文件会更容易?
    • 我在更新的答案中写了一个示例。这取决于情况。如果同时有多个请求来修改服务器状态,可能会导致一些问题。两个请求都将首先读取文件。我们假设第一个请求想要survival 在线,第二个请求想要creative 在线。但是,他们在读取文件的第一个动作中获得了所有脱机状态。第二个请求可能涵盖第一个请求修改。文件中的最后一个内容可能是{"lobby": "offline","survival": "offline","creative": "online"}survival 不会处于在线状态。
    • 所以,我认为这对分离服务器文件有好处。
    • 好的,非常感谢。有没有办法只根据 POST 请求键编辑文件?
    • 你可以把{"survival" :true}这样的请求体放在POST请求中。在您收到快递后,您可以通过req.body.survival 访问该值。然后你可以使用jsonData["survival"] = req.body.survival 来赋值。
    【解决方案2】:
    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);
    

    【讨论】:

      猜你喜欢
      • 2014-09-05
      • 2020-09-23
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      相关资源
      最近更新 更多