2
I’m using a server node.js
with express
and created an API to record content that arrived via POST
in an archive .json
.
It does the process correctly to a certain extent: If the file does not exist, it creates the file in the folder, inserts a blank array and then calls the function to fill in with the mounted object that arrived in the POST. At some times it simply inserts another object with the same name, even though an object with another name has been sent and the server falls.
Another problem is when you pass the existing Object validation, which validates the item name if there are any with the same name which has arrived, if it has, it returns a json res.json({ error: 1, message: 'Modelo já existente!' });
. At that moment, it returns this json and drops the server.
If you could give me a hand, I’d appreciate it!
Code:
app.post('/api/salvar_modelo', function (req, res) {
var nome = req.body.nome_modelo;
var codigo = req.body.codigo_modelo;
let jsondata = { 'name': nome, 'model': codigo }
let archive = 'C:/mnt/modelos/modelos.json';
let obj = [];
let json;
fs.access(archive, fs.F_OK, (err) => {
if (err) {
fs.writeFile(archive, '[]', 'utf8', (err) => {
if (err) console.log(err);
atualizarJson();
});
return
}
atualizarJson();
});
function atualizarJson() {
fs.readFile(archive, 'utf8', function(err, data) {
if (err) {
res.json({ error: 1, message: 'Erro ao salvar modelo!' });
} else {
obj = JSON.parse(data);
console.log("Entrou ");
if (obj.length != 0) {
obj.forEach(function (objc) {
if (objc.name == jsondata.name) {
console.log("Entrou 2");
res.json({ error: 1, message: 'Modelo já existente!' });
}
});
obj.push(jsondata);
json = JSON.stringify(obj);
fs.writeFile(archive, json, 'utf8', (err) => {
if (err) console.log(err);
res.json({ error: 0, message: 'Modelo salvo com sucesso!' })
});
} else {
obj.push(jsondata);
json = JSON.stringify(obj);
fs.writeFile(archive, json, 'utf8', (err) => {
if (err) console.log(err);
res.json({ error: 0, message: 'Modelo salvo com sucesso!' })
});
}
}
});
}
});
Edit: I fixed his error by deleting the contents of the file