B
B
baroman4ik2022-03-07 12:23:14
JavaScript
baroman4ik, 2022-03-07 12:23:14

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

, but returns undefined. tell me what is wrong. I read the documentation several times, but I never figured out what the error was.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DeFaNJI, 2022-03-08
@DeFaNJI

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

Perhaps like this?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question