Answer the question
In order to leave comments, you need to log in
How to implement sequential reading and writing of JSON file in node.js?
An array comes to the server, you need to push it into a json file and, if successful, read the same file and return it to the client.
Tried to do it like this:
async function writeData(data) {
data = JSON.stringify(data);
try {
fs.writeFile("localData.json", data, "utf8", async (err) => {
if (err) console.error(err);
else {
fs.readFile("localData.json", "utf8", (error, array) => {
themes = array;
return themes;
});
}
});
} catch (err) {
console.error(err);
}
app.post("/newarray", async function (req, res) {
try {
const newarray = await writeData(req.body);
console.log("newarray was successfully saved", newarray);
res.json(newarray);
} catch (err) {
console.log(err);
}
});
Answer the question
In order to leave comments, you need to log in
async function writeData(data) {
data = JSON.stringify(data);
let themes;
try {
fs.writeFile("localData.json", data, "utf8", async (err) => {
if (err) console.error(err);
else {
fs.readFile("localData.json", "utf8", (error, array) => {
themes = array
});
}
});
} catch (err) {
console.error(err);
}
if (themes) return themes;
}
app.post("/newarray", async function (req, res) {
try {
const newarray = await writeData(req.body);
console.log("newarray was successfully saved", newarray);
res.json(newarray);
} catch (err) {
console.log(err);
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question