简体   繁体   English

针对每个请求,将对象添加到Node.js中JSON文件中的数组中

[英]Add object to an array in a JSON `file` in Node.js for each request

I have an image on the frontend. 我在前端有一个图像。 When the user right clicks on the image, the coordinates of that point are stored in a variable and that variable is then sent to the node server using AJAX post request. 当用户右键单击图像时,该点的坐标将存储在变量中,然后使用AJAX发布请求将该变量发送到节点服务器。 Then in the server side I am storing the x,y coordinates into a file as objects. 然后在服务器端,我将x,y坐标作为对象存储到文件中。 I want to keep on piling up the set of x,y coordinates into that same file as different objects from the previous, when the user right clicks at other places on the image. 当用户右键单击图像上的其他位置时,我想继续将x,y坐标集作为与先前对象不同的对象堆积到同一文件中。 The problem is that when I right click on some other position, the coordinates of that point are replacing the previous ones in the file, instead of adding to the file and keeping the previous ones as well. 问题是,当我右键单击其他位置时,该点的坐标将替换文件中的前一个坐标,而不是添加到文件中并同时保留前一个坐标。 How can I achieve that? 我该如何实现?

.post(function(request, response){
    console.log("Request received");
    var util = require('util');
    var coordinates = request.body;
    var imageCoordinates = JSON.stringify(coordinates);
    fs.writeFile('coords.json', imageCoordinates, finished);

    function finished(err){
        console.log('all set.');
    }

    console.log('coords are:', coordinates);        
    response.send("All OK");
}); 

This is the request handler function in my server.js file. 这是我的server.js文件中的请求处理程序函数。

fs.writeFile: Asynchronously writes data to a file, replacing the file if it already exists. fs.writeFile:异步将数据写入文件,如果文件已经存在,则替换该文件。

fs.appendFile: Asynchronously append data to a file, creating the file if it does not yet exist. fs.appendFile:异步将数据添加到文件,如果该文件尚不存在,则创建该文件。

Code has two issues, 代码有两个问题,

use appendFile instead of writeFile, modified the code below. 使用appendFile代替writeFile,修改了以下代码。 Also you need to send the response once the write is completed. 此外,一旦写入完成,您还需要发送响应。

function finished(err){ console.log('all set.'); 完成函数(err){console.log('all set。'); response.send("All OK"); response.send(“一切正常”); } }

Otherwise response might go earlier before the write is completed. 否则,响应可能会在写入完成之前提前进行。

.post(function(request, response){
    console.log("Request received");
    var util = require('util');
    var coordinates = request.body;
    var imageCoordinates = JSON.stringify(coordinates);
    fs.appendFile('coords.json', imageCoordinates, finished);

    function finished(err){
        console.log('all set.');
        response.send("All OK");
    }

    console.log('coords are:', coordinates);        

}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM