Node.js Fs Module (File System) Tutorial

beginner
14 min

Node.js Fs Module (File System) Tutorial

Welcome to our comprehensive guide on the fs (File System) module in Node.js! This tutorial is designed to help beginners and intermediates understand the ins and outs of working with files using Node.js. Let's dive in!

What is the fs Module?

The fs module in Node.js is used to interact with the file system. It allows you to read, write, and manage files and directories in your project.

šŸ“ Note:

Understanding the fs module is crucial for any Node.js project that involves file operations.

Creating a File

To create a file, you can use the fs.writeFile() method. Here's a simple example:

javascript
const fs = require('fs'); fs.writeFile('example.txt', 'Hello, World!', (err) => { if (err) throw err; console.log('The file has been saved!'); });

šŸ’” Pro Tip: Always check for errors when working with the file system to ensure your code runs smoothly.

Reading a File

To read a file, you can use the fs.readFile() method. Here's how to read the example.txt file created earlier:

javascript
const fs = require('fs'); fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });

šŸŽÆ Key Concept:

  • The second argument 'utf8' is used to specify the encoding type.

Writing to an Existing File

To append to an existing file, you can use the fs.appendFile() method:

javascript
const fs = require('fs'); fs.appendFile('example.txt', '\nThis is an append!', (err) => { if (err) throw err; console.log('The file has been updated!'); });

Deleting a File

To delete a file, you can use the fs.unlink() method:

javascript
const fs = require('fs'); fs.unlink('example.txt', (err) => { if (err) throw err; console.log('The file has been deleted!'); });

šŸ“ Note:

Remember to check for errors to avoid unexpected issues.

Quiz Time!

Quick Quiz
Question 1 of 1

What method would you use to create a new file in Node.js?

Stay tuned for more on the fs module, including working with directories and advanced file system concepts!