0

I have this situation where I'm trying to send a request with the content of a file, but the problem is that the content arrives undefined. How can I solve this? I tried multiple versions from stackoverflow, but nothing worked so far.

const ifExists = (filePath) => {
    try {
        if (fs.existsSync(filePath)) {
            return true;
        }
    } catch (err) {
        console.log(err);
    }
    return false;
}

const readMyFile = async (filePath) => {
    const fileExists = ifExists(filePath);
    if (fileExists) {
        fs.readFile(filePath, (err, data) => {
            if (err) {
                console.log("Error occurred when trying to read the file.");
                return false;
            }
            console.log("File successfully read.");
            return data; // data has the right content here
        });
    } else {
        console.log("File not found");
        return false;
    }
}

const getFile = async function (req, res, next) {
    try {   
        const content = await readMyFile(filePath); // the content is undefined here
        res.writeHead(200, { "Content-Type": "application/json" });
        res.write(JSON.stringify(content));
    } catch (err) {
        console.log("Error occurred.");
        res.status(500).send("Error");
    } finally {
        res.end();
    }
};

Thank you for your time!

Tenzolinho
  • 922
  • 2
  • 15
  • 35

1 Answers1

0

fs.readFile uses a callback and does not return a promise which means it can't be used properly in an async function. If you want to use an async function I suggest returning a promise.

const readFile = async (filePath) => {
  return new Promise((resolve, reject) => {
    if (!exists(filePath)) {
      reject(Error("File not found"));
    }

    fs.readFile(filePath, (err, data) => {
      if (err) {
        reject(err);
      }
      resolve(data)
    });
  })
}
Evans M.
  • 1,791
  • 16
  • 20
  • 1
    note that I renamed your ifExists to exists for readability since it has to be called inside an if statement – Evans M. Aug 21 '20 at 09:18
  • Thank you for your answer. But I can't figure it out why is this working (tbh I don't work with `Promises`), and what is wrong with `async/await` syntax? I mean, can this be written with `async/await` instead of `Promise`? What I did wrong there? – Tenzolinho Aug 21 '20 at 09:49
  • Oh, I think I get that, to use `async/await` I need methods that return promises, and `readFile` does not do that. – Tenzolinho Aug 21 '20 at 09:57