Node File System Basics
KrishnaKanth
DeveloperNode.js comes with a built-in File System (fs) module that has all the features needed to perform CRUD operators on local files and folders. First install NodeJS if you haven't already.
If you want to follow along in the editor, create a index.js
file to to run each of the examples. Import the fs module at the top
We can run this file for each example using
The file system has a variety of methods available such as opening, editing, deleting files, etc that we can use. Each method has an asynchronous and synchronous version available to use. The shorter method name is always asychronous, while the synchronous one has Sync at the end.
fs.appendFile()
is asynchronousfs.appendFileSync()
is synchronous
Both methods generally achieve the same thing so choose the one that makes the most sense for your situation
Here are some of the methods you can call using the fs module
File system Method | What it does |
---|---|
appendFile | Appends text to a file |
mkdir | Creates a directory (or multiple) |
readDir | Reads the contents of a directory |
readFile | Reads a file |
writeFile | Writes text to a file |
unlink | Deletes a file |
Each method generally accepts a path or file string as the first argument.
Create Files and Folders
Create Files
To create a new file, use the writeFile
method to write a blank string. This will create a new file if the file doesn't already exist
Create folders
Create one or multiple nested folders using the filesystem like so
Write to a File
There are two methods to write to a file, depending on if you want to add text or overwrite text. The first method, writeFile
will overwrite whatever text is in a file
The other method, appendFile
will create a new file if it doesn't exist, and append text to the end if it does
Read Files and Folders
Read a file
We can read our list.txt
file from above with the readFile
method
Synchronous methods are sometimes easy to code for example we could shorten the above code to
Read a folder
We can also read folders with the following readdir
method
This method will return the names of the contents of the folder, whether they are files or folders.
Delete Files
Lastly, we can delete files with the unlink
method
Making HTML and JS Files
The fs module is great for working with any types of text files including .txt, .js, and even .html. For example we can include whatever file type we need like so
There are plenty of cool features in the file system you can use to build out interesting applications such as editors, note-taking apps, and more.