2

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"
}
1
  • Read the file, parse the JSON, modify the JSON, write file Commented Feb 12, 2018 at 4:41

2 Answers 2

4

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:

  1. Reads the data from the file.
  2. Modifies the data to get the new data the file should have.
  3. Write the data(NOT append) back to the file.
Sign up to request clarification or add additional context in comments.

Comments

0

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)
  })
})

1 Comment

Don't throw synchronously inside a callback, use their async counterparts

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.