File I/O
Node.js File System
Node.js File System
Node.js file system uses fs module for reading and writing files.
Introduction to Node.js File System
The Node.js File System (fs) module is a built-in module that allows you to work with the file system on your computer. It provides a suite of methods for interacting with files and directories, such as reading, writing, deleting, and renaming files.
In this post, we'll explore the basics of the fs module and how to use it for common file operations.
Importing the fs Module
To begin working with the file system in Node.js, you need to import the fs module using the require
function. This allows you to access all the functionalities provided by the module.
Reading Files
Reading files is a fundamental operation in any file system. Node.js provides several methods to read files, including synchronous and asynchronous approaches. Here's how you can read a file asynchronously:
In this example, fs.readFile
takes the file path, encoding, and a callback function. If the file is read successfully, the data is passed to the callback function; otherwise, an error is returned.
Writing Files
Writing to files is just as important as reading them. Node.js allows you to write data to a file using the fs.writeFile
method. This method is also asynchronous.
The fs.writeFile
method takes the file path, data to write, and a callback function. If the operation is successful, it logs a confirmation message.
Appending to Files
Sometimes, you might want to add data to an existing file without overwriting it. Node.js provides the fs.appendFile
method to achieve this.
In this example, fs.appendFile
adds a new line of text to example.txt
without removing existing content.
Deleting Files
Node.js makes it easy to delete files using the fs.unlink
method. This method is asynchronous and takes the file path and a callback function.
Here, fs.unlink
removes example.txt
from the file system. If successful, it logs a confirmation message.
File I/O
- File System
- File Reading
- File Writing
- File Streams
- File Paths
- File Deletion
- Previous
- Error Handling
- Next
- File Reading