In almost every application, you come to a point where you need to access the filesystem. This is an essential skill, that I personally use as a starting point when learning a new language or platform. With Node.js, you can rely on built-in modules to work with the filesystem. Common tasks in this regard usually include:
Due to the asynchronous nature of Node.js, coding these tasks might be a bit different from what can be seen in other languages/platforms, so it's always interesting to make sure you're starting with the right habits.
To get started with these tasks, I'll leave you in the hands of my friend Aaron Powell, with short videos that run for less than 5 min each.
fs
and path
modules workfs
and path
modulesOut of the box, Node.js comes with two built-in modules that you can use to work with the filesystem:
fs
and path
. Let's take a quick look at them to see how they work, and what they can be used for.Exploring directories to list the contents and file or filter particular files may sometimes be a bit challenging at the beginning, especially when using the asynchronous API. But instead of a plain explanation on how to do that, let's code it using a practical example. If you want to follow along, you'll find the code on this repo.
Sometimes manipulating the filesystem paths can be tricky, especially for cross-platform applications (looking at you, Windows 👀). Let's consider a practical use case like accessing the current file path of your program and see how to construct paths from it.
Creating new files is probably the main subject here. You'll have to make sure the folder containing them exist, and create it if it doesn't. The logic for checking whether files or folders exist may be a bit different from what you may be used to, so let's check that too.
Reading a file might seem an easy job, but there's always the tricky question of character encoding. When writing text files, Node.js use UTF-8 encoding as the default, but you need to specify it when reading files otherwise you might be in for some surprises. Let's see how it goes for reading and updating JSON files, as it can be quite useful when manipulating app configurations.
We're done for this post, but that doesn't mean that you should stop there. You should consider this post as a practical crash course on using the filesystem with Node.js. And of course, there's a lot more to it than what we can cover under 5 minutes videos. In particular, I would like to bring to your attention potential issues if you're working with different OS filesystems, as it's easy to trip over.
If you would like to deepen your knowledge around filesystem manipulation, you can take a look at this Interactive in-depth tutorial on Node.js filesystem.
Thanks for reading!
Also published at https://dev.to/sinedied/work-with-files-and-directories-in-a-node-js-app-4kh8