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');
});
How can I separate each object by comma?
– Charles Fonseca
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...– Vítor Ferragini