If you've ever wanted to manipulate files using Node.js, you're in the right place! Meet the fs
module—Node.js' built-in file system manager. Whether you're reading files, writing data, creating directories, or deleting unwanted files (bye-bye, junk!), the fs
module is your best friend.
So, grab a cup of coffee , and let’s dive into file magic with Node.js!
What Is the fs
Module in Node.js?
The fs
(file system) module is a core module in Node.js that allows you to interact with the file system. You can use it to:
- Read files
- Write files
- Append data to files
- Delete files
- Work with directories (create, remove, check existence)
And best of all? You don’t need to install anything—it’s built right into Node.js!
To use it, just require it at the top of your script:
const fs = require('fs');
Boom! Now you’re ready to control files like a Node.js ninja.
Reading Files with fs.readFile()
Let's start by reading a file. Suppose you have a file named hello.txt
that contains:
Hello, Node.js! This is a sample file.
You can read it using:
const fs = require('fs');
fs.readFile('hello.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
console.log('File content:', data);
});
Explanation:
'utf8'
ensures the file is read as a text file, not raw bytes.- The callback function receives two arguments:
err
(if an error occurs) anddata
(the file content). - If there's an error (e.g., the file doesn’t exist), we handle it gracefully.
Writing to Files with fs.writeFile()
Want to create a new file or replace its contents? Use fs.writeFile()
:
fs.writeFile('newfile.txt', 'Hello, this is Node.js writing to a file!', (err) => {
if (err) {
console.error('Error writing file:', err);
return;
}
console.log('File written successfully!');
});
Run this, and Node.js will create newfile.txt
if it doesn’t exist. If it already exists, it will overwrite its contents.
Appending Data to Files with fs.appendFile()
What if you don’t want to overwrite the file but just add more text? Use fs.appendFile()
:
fs.appendFile('newfile.txt', '\nThis is an extra line.', (err) => {
if (err) {
console.error('Error appending file:', err);
return;
}
console.log('Data appended successfully!');
});
This will add a new line at the end of newfile.txt
instead of replacing its content.
Deleting Files with fs.unlink()
Accidentally created too many files? Time to clean up! 🧹 Use fs.unlink()
to delete a file:
fs.unlink('newfile.txt', (err) => {
if (err) {
console.error('Error deleting file:', err);
return;
}
console.log('File deleted successfully!');
});
Warning: There’s no "Undo" button, so use this carefully!
Creating a Directory with fs.mkdir()
Need to create a new folder? Just use fs.mkdir()
:
fs.mkdir('myFolder', (err) => {
if (err) {
console.error('Error creating folder:', err);
return;
}
console.log('Folder created successfully!');
});
Success! Now you have a brand-new folder named myFolder
.
Checking If a File or Folder Exists
Before performing file operations, it’s a good idea to check if a file or folder exists. Use fs.existsSync()
:
if (fs.existsSync('hello.txt')) {
console.log('File exists!');
} else {
console.log('File does not exist.');
}
Why use this? If you're about to read a file, but it doesn't exist, you’ll avoid errors.
Reading a Directory with fs.readdir()
Want to list all files in a folder? Use fs.readdir()
:
fs.readdir('.', (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
console.log('Files in directory:', files);
});
This will list all files and folders inside the current directory (.
).
Renaming a File with fs.rename()
Let’s rename a file:
fs.rename('hello.txt', 'greeting.txt', (err) => {
if (err) {
console.error('Error renaming file:', err);
return;
}
console.log('File renamed successfully!');
});
Now hello.txt
is renamed to greeting.txt
.
Reading Files Synchronously (Blocking Mode)
So far, all our functions have been asynchronous (non-blocking). But what if you want to read files synchronously?
const data = fs.readFileSync('hello.txt', 'utf8');
console.log('File content:', data);
Warning: Synchronous methods block execution, so use them only when necessary (like in startup scripts).
Using fs.promises
(Modern Async/Await)
Node.js also provides Promises-based file handling, which works great with async/await.
Example:
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('hello.txt', 'utf8');
console.log('File content:', data);
} catch (err) {
console.error('Error reading file:', err);
}
}
readFile();
Why use this?
- No more nested callbacks ("callback hell").
- Clean and readable code.
Conclusion
You’ve just mastered the fs
module in Node.js! Now you can:
- Read, write, and append files.
- Delete files and directories.
- Check if files exist.
- Use synchronous and asynchronous methods.
- Work with modern
fs.promises
for clean async/await code.
The file system is one of the most powerful parts of Node.js, and now you can manipulate files like a pro.
0 Comments