How to write in json without overwriting?

Asked

Viewed 322 times

1

How can I write to a file, for example test.json, concatenating with what’s in it (without overwriting)? I’m doing it this way, however, it’s overwriting.

const fs = require('fs');
const file = __dirname + '/teste.json';

const produto = {
    nome: 'Smartphone',
    preco: 1749.99,
    desconto: 0.15
};

fs.writeFile(file, JSON.stringify(produto), err => {
    console.log(err || 'Arquivo salvo');
});

1 answer

2


To add content to the file without overwriting, you should use the function appendFile().

The function writeFile() will always replace the file with a new.

const fs = require('fs');
const file = __dirname + '/teste.json';

const produto = {
    nome: 'Smartphone',
    preco: 1749.99,
    desconto: 0.15
};

fs.appendFile(file, JSON.stringify(produto), err => {
    console.log(err || 'Arquivo salvo');
});
  • How can I separate each object by comma?

  • You can read the file, use a JSON.parse() to convert the read data to JSON, add the new object with a push, and then write the file (in that case, you could use writeFile even, since it would overwrite with the full object). But the bigger the file, the slower it would be...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.