Node.js how to delete \ edit data inside json file on server

I am running node express server and I am using

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

to get data inside json on the server. json with data looks like this:

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

How (what request to execute) delete \ modify any object in this json?

+4
source share
1 answer

To read the JSON file, you can use the jsonfile module . Then you need to determine the route puton the express server. A snippet of code for an express server that highlights the vital parts:

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;
      });
    });
});
+2
source

Source: https://habr.com/ru/post/1625562/


All Articles