Sitemap

Node: the fs Module

3 min readApr 5, 2020

--

The fs module is a convenient library for Node, that provides a ton of functions for controlling how the data is stored on a hard drive, as well as how it is accessed and managed on the operating system. So, I’m sure you’ll be surprised to hear what fs stands for. Well, before you waste all your brain power on figuring it out, I’ll just tell you that it stands for file system.

A couple important things to note about the fs module for Node is that it works asynchronously by default, and that you never have to install it. While fs does work asynchronously, it can work synchronously, if you want it to; all that you have to do is add “Sync” to the function name. To use it on any project, all you have to do is require it at the top of the file, with a simple require line.

Press enter or click to view image in full size

Above I’ve added a function that creates (or writes) a new file asynchronously. You’ll notice that I required fs at the top, you have to do this in each file where you use a fs function. Next, you might notice that I said this function works asynchronously, this is extremely useful and convenient, but if you wanted it to work synchronously, all you’d have to do is add the word “Sync” just before the yellow open parenthesis on line 3. You might also notice that I made this function ready to throw errors if they exist, it’s usually a good idea to do this in your fs functions.

Press enter or click to view image in full size

Next, I’ve made a function to read files synchronously, you’ll notice that for this one I did not need a require statement, that’s because these functions are in the same file, and so the first require statement is enough. I’ve also chosen to make this one a synchronous function to demonstrate how simple it is to switch back and forth with the fs module. If, you wanted to make this one asynchronous all you’d have to do is remove the “Sync” portion of the function call. You may have also noticed, that this one has an entire file path instead of just the name of a file as one of its parameters. This is because it’s required to be passed that way for the read function.

Get Ben Meyers’s stories in your inbox

Join Medium for free to get updates from this writer.

There may be around a billion functions as part of the Node-fs module. I encourage you to check them out, and find some that work for your next Node project. Here is website with lots of documentation: https://nodejs.org/api/fs.html

Press enter or click to view image in full size

I hope that this article inspired you to use the Node — fs module, and maybe helped you learn a bit about how it all works. Have a wonderful day!

--

--