Lonster_Monster
Lonster_Monster

Reputation: 73

How to Remove last Character in json file with node js

I am using Nodejs and i am learning more about the fs module. The data storage file type i have been using is JSON.

I am fairly new to the fs module and want to take the last } of my stock.json out to enter new data and put it back in so it can be called later in my full code

Here is the code i am trying to use

fs.readFile(filestockname, "UTF8", function(err, data) {
            if (err) { throw err };
            global_data = data;
            var stocknames = item
            console.log("File Read")
            fs.writeFileSync('.//settings/Stock/stock.json', global_data+"\r\n" +'"'+stocknames+'"'+"\r\n"+"{"+"\r\n"+'"'+"instock"+'"'+":"+ "1"+"\r\n"+'"'+"stocklimit"+'"'+":"+ "200"+"\r\n"+"}", (err) => {
            if (err) throw err;
            });
            });
        }

Here is the code that is in my stock.json

}
    "Scrap Metal":{
    "instock":1,
    "stocklimit":200
    }
}

Upvotes: 0

Views: 1441

Answers (1)

Sven
Sven

Reputation: 5265

Luckily for us we don't have to parse & encode raw JSON data ourselves, but we can rather use JavaScript's built-in JSON.parse() and JSON.stringify() methods, which lets us work with standard JavaScript data structures, like Object, Array, String, and so on.

fs.readFile(filestockname, "UTF8", (err, data) => {
  if (err) throw err;
  let global_data = JSON.parse(data);
  global_data[item] = {
    instock: 1,
    stocklimit: 200
  };
  console.log("File Read");
  fs.writeFile('.//settings/Stock/stock.json', JSON.stringify(global_data), (err) => {
    if (err) throw err;
    console.log("File Written");
  });
});

Upvotes: 1

Related Questions