Node.js如何删除\编辑服务器上的json文件内的数据

我运行快递节点服务器,我使用

$.ajax({ url: this.props.url, dataType: 'json', cache: false, success: function(data) { this.setState({data: data}); }.bind(this), error: function(xhr, status, err) { console.error(this.props.url, status, err.toString()); }.bind(this) }); 

在服务器上获取json内部的数据。 json的数据如下所示:

 [ { "id": 1453464243666, "text": "abc" }, { "id": 1453464256143, "text": "def" }, { "id": 1453464265564, "text": "ghi" } ] 

如何(请求执行)删除\修改此json中的任何对象?

要阅读JSON文件,可以使用jsonfile模块。 然后,您需要在快递服务器上定义put路线。 快速服务器代码片段突出重要部分:

app.js

 // This assumes you've already installed 'jsonfile' via npm var jsonfile = require('jsonfile'); // This assumes you've already created an app using Express. // You'll need to pass the 'id' of the object you need to edit in // the 'PUT' request from the client. app.put('/edit/:id', function(req, res) { var id = req.params.id; var newText = req.body.text; // read in the JSON file jsonfile.readFile('/path/to/file.json', function(err, obj) { // Using another variable to prevent confusion. var fileObj = obj; // Modify the text at the appropriate id fileObj[id].text = newText; // Write the modified obj to the file jsonfile.writeFile('/path/to/file.json', fileObj, function(err) { if (err) throw err; }); }); });