收到 POST 请求并编辑 JSON 文件 NodeJS

Receive POST request and edit JSON file NodeJS

在收到来自 NodeJS 客户端的 POST 请求后,我不知道如何编辑我的 json 文件。

使用 webix 数据table。在我更新 table 中的数据后,它会发送一个 POST 请求,其中包含已进行的数据 + 操作( webix_operation=update /delete /insert )所以我想我可以做这样的事情:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended : true }));

app.post("/Page2", function (req, res) {
    var operation = req.body.webix_operation;

    if (operation == 'update') {
        fs.readFile("JSON/DB.json", "utf8", function (err, data) {
            var allData = JSON.parse(data)
            var userData = {
                "id": req.body.id,
                "data1": req.body.data1,
                "data2": req.body.data2,
                "data3": req.body.data3,
            }
            allData.push(userData);
            var newData = JSON.stringify(allData);
            fs.writeFile("JSON/DB.json", newData, "utf8");
            console.error(err.stack);
        })
        res.send();
    }
    else if (operation == 'insert') {
    }
    else if (operation == 'delete') {

    }
    else
        console.log("This operation is not supported")
});

但是不行。

有人可以检查代码并找出我做错了什么吗?

app.post("/Page2", function (req, res, next) {
    var operation = req.body.webix_operation;

    if (['insert', 'update', 'delete'].indexOf(operation) == -1)
       return next(new Error('Bad request'));

    // More better use http post to insert, put to update, delete to delete
    // e.g. app.put('/page2', func) to update

    var userData = {
        id: req.body.id,
        data1: req.body.data1,
        data2: req.body.data2,
        data3: req.body.data3
    }

    if (!userData.id)
        return next(new Error('id is not set'));

    fs.readFile("JSON/DB.json", "utf8", function (err, data) {
        if (err)       
            return next(err);

        var allData;
        try {
            allData = JSON.parse(data);
        } catch(err) {
            return next(err);
        }

        // find index of element in allData
        var i = allData.reduce(function(iRes, e, iCurr) {
             return (e.id == userData.id) ? iCurr : iRes
        }, -1);

        if (i == -1 && (operation == 'update' || operation == 'delete'))
            return next(new Error(operation + ': Bad id'));


        if (operation == 'update') 
            allData[i] = userData;

        if (operation == 'delete') 
            allData.splice(i, 1);

        if (operation == 'insert') 
            allData.push(userData);

        fs.writeFile("JSON/DB.json", JSON.stringify(allData), 'utf8', function (err) {
            if (err)
                return next(err);

            res.end(); 
        })      
    }); // end of readFile
});
...
app.use(function(err, req, res, next)) {
    console.log(req.url, err);
    res.end(err.message); 
}