Node.js and FS.readFile
During the process of trying to learn all-the-things-about-Node-in-4-days, I was tasked with retrieving data from a stored file. A file system, you say? This sounds like a job for Node’s FS library. After scanning through some of the documentation, the fs.readFile method seemed like a likely place to start.
While the readFile seems like a simple function to use, it didn’t seem to be cooperating. I had been asking it to serve up the html file it had been reading when it ended, but instead it was sending my default “Hello world!” string. While very friendly, it’s not exactly the optimal user experience.
It turns out, it’s easy to forget that fs.readFile is asynchronous by nature. This means it might not have the data necessary to complete the function as expected before it continues on to other processes. To take care of this, any actions you need to take must be done within the callback function and then it should work as expected.
On to the next problem!