Node.js provides a powerful and flexible file system (fs) module for interacting with files. This tutorial will guide you through the basics of reading, writing, and manipulating files in Node.js.
Node.js File System Basics
1. Introduction to the File System Module
In Node.js, the fs module is used to interact with the file system. It allows you to perform actions such as reading and writing files, creating directories, and more.
2. Importing the File System Module
To work with the fs module, you need to import it into your Node.js application:
const fs = require('fs');
3. Reading Files
To read a file asynchronously, use the `fs.readFile()` method:
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
This reads the contents of the `example.txt` file and logs it to the console. The callback function handles any errors and outputs the data if the file is read successfully.
4. Writing Files
To write data to a file, use the `fs.writeFile()` method:
fs.writeFile('output.txt', 'Hello, Node.js!', (err) => {
if (err) throw err;
console.log('File written successfully!');
});
This writes the string "Hello, Node.js!" to the file `output.txt`. If the file doesn't exist, it will be created.
5. Appending to Files
To append data to an existing file, use the `fs.appendFile()` method:
fs.appendFile('output.txt', ' This is more content!', (err) => {
if (err) throw err;
console.log('Data appended successfully!');
});
This appends the text " This is more content!" to the `output.txt` file.
6. Deleting Files
To delete a file, use the `fs.unlink()` method:
fs.unlink('output.txt', (err) => {
if (err) throw err;
console.log('File deleted successfully!');
});
This deletes the `output.txt` file from the system.
7. Conclusion
Using the Node.js File System (fs) module, you can perform a variety of tasks related to files, such as reading, writing, appending, and deleting. These operations are essential for building applications that interact with the file system, enabling you to manipulate files for various purposes.
Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.