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

西贝里奇

我正在运行Express Node Server,我使用

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在窗口服务器上的后台进程中运行Node js文件?

如何从浏览器上的网页更新 Node.js 服务器上的 JSON 数据?

如何在Node.js服务器上的多个客户端之间同步数据

如何在Node.js服务器上使用HTTP POST数据?

如何在Node.js服务器上用XML文件填充ElasticSearch?

如何在运行Node.js的服务器上保存文件?

Javascript/Node.js 服务器 - 查询 JSON 文件中的数据集以创建 URL

如何在在线服务器上启动Node JS服务器?

如何在Node.js服务器上的Functions中访问Firebase存储?

如何在Node.js服务器中包含JavaScript文件的功能?

如何在Node.js中的服务器目录上方获取文件

如何在node.js服务器上的多个客户端之间同步数据库文件而不下载那些已经下载的文件?

如何在node.js服务器上向客户端ajax请求提供json文本文件

如何在Node.js中的浏览器上从CSV文件打印数据

Node.js从服务器渲染大量JSON数据

如何在 Node.js 中从客户端获取数据到服务器(不带 url 参数)?

如何使用Angular Js以从node.js服务器检索的表格式显示json数据

如何在Handlebars(客户端)中打印从Node JS服务器发送的JSON对象数组?

在Node.js服务器上的内存存储中

如何直接访问Hapi(Node.js)服务器上的文件?

如何在服务器上使用调度程序自动运行Node js脚本

如何在服务器上执行Node.js脚本?

如何在Linux AWS上重启Node.js服务器

如何在Node.js服务器上显示我的网站?

如何在本地为node.js服务器启动mysql数据库?

如何在Node.js中下载HTTP Web服务器上托管的文件

如何在Node.js中将文件从服务器发送到客户端

如何在我的网站服务器而不是PC本地服务器中运行node.js

如何从Node JS服务器读取JSON响应?