fs.readFile
is an asynchronous operation. That means it returns
before the file has been read.
The file data won't be available until the operation has completed and the callback function has been called.
If you're using a recent version of Node, you can use the Promise-returning API
fsPromises.readFile
instead:
File system | Node.js v18.4.0 Documentation[
^]
That will let you execute the rest of your code when the operation has completed.
You could even use it with
async
and
await
to simplify the code:
Modern Asynchronous JavaScript with Async and Await[
^]