I'm trying to add a new text to an existing json file, I tried writeFileSync and appendFileSync however the text added doesn't format as json even when i use JSON.stringify.
const fs = require('fs');
fs.readFile("test.json", (err, data) => {
if( err) throw err;
var data = JSON.parse(data);
console.log(data);
});
var student = {
age: "23"
};
fs.appendFileSync("test.json", "age: 23");
// var writeData = fs.writeFileSync("test.json", JSON.stringify(student));
My json file
{ name: "kevin" }
Append turns out like this, {name: "kevin"}age: "23" and writeFileSync turns out like {name: "kevin"}{age: "23"}
What I want is to continuously add text to my json file like so
{
name: "kevin",
age: "23"
}
First, dont use readFileSync
and writeFileSync
. They block the execution, and go against node.js standards. Here is the correct code:
const fs = require('fs');
fs.readFile("test.json", (err, data) => { // READ
if (err) {
return console.error(err);
};
var data = JSON.parse(data.toString());
data.age = "23"; // MODIFY
var writeData = fs.writeFile("test.json", JSON.stringify(data), (err, result) => { // WRITE
if (err) {
return console.error(err);
} else {
console.log(result);
console.log("Success");
}
});
});
What this code does:
Here's what you can do: read the data from the file, edit that data, then write it back again.
const fs = require("fs")
fs.readFile("test.json", (err, buffer) => {
if (err) return console.error('File read error: ', err)
const data = JSON.parse(buffer.toString())
data.age = 23
fs.writeFile("test.json", JSON.stringify(data), err => {
if (err) return console.error('File write error:', err)
})
})
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.