NodeJS File Systems
Let’s talk about the File System in NodeJS now that can enhance your file handling capabilities.
1. Setting up the Project
Create a new directory for your project and navigate to it in your terminal. Initialize a new Node.js project by running the following command:
This will generate a package.json file for your project.
2. Installing the Required Modules
Install the fs module, which provides file system functionality in Node.js, by running the following command:
3. Reading a File (fs.readFile)
To read a file, you can use the fs.readFile method. Here's an example that reads the contents of a file and logs them to the console:
Replace 'file.txt' with the path to the file you want to read. The second argument, 'utf8', specifies the file's encoding. The callback function is executed when the file reading is complete, and any errors or the file's contents are passed as arguments.
4. Writing a File Synchronously (fs.writeFileSync)
The first argument passed to fs.writeFileSync is the file path, and the second argument is the content to write. If an error occurs, it will be caught and logged to the console.
5. Writing a File Asynchronously (fs.writeFile)
The first two arguments passed to fs.writeFile are the file path and the content to write. The third argument is a callback function that is executed when the file writing is complete, or if an error occurs.
6. Opening a File (fs.open)
The first argument passed to fs.open is the file path, and the second argument specifies the mode in which the file should be opened (e.g., 'r' for reading, 'w' for writing). The callback function is executed when the file is opened or if an error occurs. Inside the callback, you can perform further operations on the file if needed. Finally, the fs.close method is used to close the file.
7. Deleting a File (fs.unlink)
The first argument passed to fs.unlink is the file path. The callback function is executed when the file is deleted or if an error occurs.
8. Running the Examples
Make sure to replace readFileExample.js with the name of the file you want to run.
That's it! You've learned how to work with file systems in Node.js. In the next tutorial, we are going to learn about Event in NodeJS.