简体   繁体   中英

Node.js write to existing Geolocation JSON error

I am trying to get used to the basics of nodejs I am trying to push data to an existing JSON file, but I get an Cannot read property 'push' of undefined.

Code:

    var obj = {
       table: []
    };
        var app =  express();    
        app.get('/parseData', function (req, res) {
              var fs = require('fs');
              fs.readFile('./json/locationData.json', 'utf8', function readFileCallback(err, data){
                  if (err){
                      console.log(err);
                  } else {
                  obj = JSON.parse(data); //now it an object
                  obj.table.push({ "type": "Feature",
                    "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
                    "properties": {"prop0": "value0"}}
                  ); //add some data
                  json = JSON.stringify(obj); //convert it back to json
                  fs.writeFile('./json/locationData.json', json, 'utf8', callback); // write it back
res.header("Content-Type",'application/json');
      res.send(json);
              }});
            });
            app.listen(3000);

JSON File:

 { "type": "FeatureCollection",
      "features": [
        { "type": "Feature",
          "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
          "properties": {"prop0": "value0"}
          },
         { "type": "Feature",
          "geometry": {"type": "Point", "coordinates": [103.0, 0.5]},
          "properties": {"prop0": "value0"}
          }
        ]
      }

table is missing from the JSON file

Once you load the file and call obj = JSON.parse(data);

obj.table no longer exists, as it will overwrite what you defined above.

Use features instead of table like this.

/* GET home page. */
router.get("/", function(req, res, next) {
  fs.readFile("locationData.json", "utf8", function readFileCallback(
    err,
    data
  ) {
    var obj = {
      table: []
    };
    if (err) {
      console.log(err);
    } else {
      obj = JSON.parse(data); //now it an object
      obj.features.push({
        type: "Feature",
        geometry: { type: "Point", coordinates: [102.0, 0.5] },
        properties: { prop0: "value0" }
      }); //add some data
      json = JSON.stringify(obj); //convert it back to json
      fs.writeFile("locationData.json", json, "utf8", function(err, data) {
        console.log("Done");
      }); // write it back
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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