I'm trying to make a REST api to hold json files for contacts, for some reason my endpoint responds before it should.
const fs = require("fs/promises");
app.get("/contacts", async (req, res) => {
let dir_name = "./contacts";
let contacts = [];
await fs.readdir(dir_name).then(async (filenames) => {
filenames.forEach(async (filename) => {
await fs.readFile(`${dir_name}/${filename}`, "utf-8").then((jsonString) => {
contacts.push(JSON.parse(jsonString));
console.log(contacts);
});
});
});
console.log(contacts);
res.send(contacts);
});
This code just results in [] being sent in response but the console.log under the json parse prints the result I'm expecting. I figured that I'm using the await keyword wrong but I'm stuck. Note: /contacts is a valid directory.