Node FS Module
#
WhyThe built-in Node.js file system module helps us store, access, and manage data on our operating system. Commonly used features of the fs module include fs.readFile
to read data from a file, fs.writeFile
to write data to a file and replace the file if it already exists, fs.watchFile
to get notified of changes, and fs.appendFile
to append data to a file. The fs core module is available in every Node.js project without having to install it.
#
What#
Node.js as a File ServerThe Node.js file system module allows you to work with the file system on your computer.
To include the File System module, use the require()
method:
Common use for the File System module:
- Read files
- Create files
- Update files
- Delete files
- Rename files
#
Read FilesThe fs.readFile()
method is used to read files on your computer.
Assume we have the following HTML file (located in the same folder as Node.js):
We can Create a Node.js file that reads the HTML file, and returns the content:
Start your server, and go to http://localhost:3000 to see the result!
#
Create FilesThe File System module has methods for creating new files:
fs.appendFile()
fs.writeFile()
Let’s see them in action!!
The fs.appendFile()
method appends specified content to a file. It will only create a file if the file does not already exist:
The fs.writeFile()
method creates a new file with the specified content. Whether the file already exists or not, a new file will be created:
#
Delete FilesYou can use the fs.unlink()
method to delete a specified file:
#
Rename FilesYou can use the fs.rename()
method to rename a specified file. The first argument is the specified file, and the second is the updated name for the file:
#
Working with FoldersThe File System module has methods for creating, accessing, reading, and deleting folders:
fs.mkdir()
fs.readdir()
fs.rename()
fs.rmdir()
fs.mkdir()
creates a new folder, whether it exists or not. We can combine fs.existsSync()
to add logic to only create the folder if it does not already exist.
fs.readdir()
reads the content of a folder and returns the relative path for the files and subfolders within:
Renaming a folder is similar to renaming a file:
Lastly, we can remove a folder or directory with fs.rmdir()
Notice that we specified { recursive: true }
. If you have content in a folder or subfolder you are trying to delete, rmdir
will throw an error, unless you include the recursive removal option.
NOTE: This method (including recursive as an option) will soon be deprecated. You can either use an npm module (i.e.
fs-extra
, and it’s.remove()
method *recommended), or use the following example after node version 14.14.0^
#
Path ModuleSo far, we’ve been using file names directly. We can use the path module to access paths to our files. Here are a few useful methods:
path.join()
- joins two parameters into a pathpath.dirname()
- returns the folder pathpath.basename()
- returns the last file/folder of the pathpath.extname()
- returns the file extensionpath.parse()
- returns an object with root, dir, base, name and ext
To visualize the differences, the results of the code above would resemble:
Method | Output |
---|---|
join | C:\Users\brbry\repos\node_fs\source\test.txt |
dirname | /source |
basename | test.txt |
extname | .txt |
parse | { root: "/", dir: "/source/", base: "test.txt", ext: ".txt", name: "test" } |
#
HowSo let's use the file system and path modules to get the path of a certain file, and read its contents
First , we need to require the fs and path modules:
Next, we’ll use the path module to store the correct file path in variable ‘dataPath’:
Then, we need to call the asynchronous version of the readFile() function:
NOTE: Node.js is single threaded, if you are using node to build the backend for your application, you might have hundreds or even thousands of clients connected to that backend, and if you keep that single thread busy, you won't be able to serve many clients. That is why we use asynchronous methods as much as possible.
Now with the above code, run node app.js
Since we have node installed, we can use the ‘node’ command to run our app.js file. Above, the file is run, and my contacts.json file contents are printed to the console.
#
Takeaways- The
fs
module let's us utilize file system I/O operations - The
fs
module can be used with thehttp
module to create a file server - The
path
module helps parse file paths