针对每个请求,将对象添加到Node.js中JSON文件中的数组中 [英] Add object to an array in a JSON `file` in Node.js for each request

查看:268
本文介绍了针对每个请求,将对象添加到Node.js中JSON文件中的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在前端有一个图像.当用户右键单击图像时,该点的坐标将存储在变量中,然后使用AJAX发布请求将该变量发送到节点服务器.然后在服务器端,我将x,y坐标作为对象存储到文件中.当用户右键单击图像上的其他位置时,我想继续将x,y坐标集作为与先前对象不同的对象堆积到同一文件中.问题是,当我右键单击其他位置时,该点的坐标将替换文件中的前一个坐标,而不是添加到文件中并同时保留前一个坐标.我该如何实现?

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. Then in the server side I am storing the x,y coordinates into a file as objects. 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. 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");
}); 

这是我的server.js文件中的请求处理程序功能.

This is the request handler function in my server.js file.

推荐答案

fs.writeFile::将数据异步写入文件,如果文件已经存在,则将其替换.

fs.writeFile: Asynchronously writes data to a file, replacing the file if it already exists.

fs.appendFile::将数据异步追加到文件中,如果该文件尚不存在,则创建该文件.

fs.appendFile: Asynchronously append data to a file, creating the file if it does not yet exist.

这篇关于针对每个请求,将对象添加到Node.js中JSON文件中的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆