Node.js / Node.js File System
Reading and Writing Files in Node.js
This tutorial will guide you through the process of reading and writing files in Node.js. You'll learn how to open, read, write, and close files using the fs module provided by No…
Section overview
5 resourcesCovers working with the file system to read, write, and manipulate files in Node.js.
Reading and Writing Files in Node.js
1. Introduction
This tutorial aims to provide a step-by-step guide to reading and writing files in Node.js. We'll use the built-in fs (file system) module in Node.js to open, read, write, and close files.
By the end of this tutorial, you'll learn:
- How to include the
fsmodule in your Node.js application - How to read files using the
fsmodule - How to write to files using the
fsmodule
Prerequisites: Basic understanding of JavaScript and Node.js.
2. Step-by-Step Guide
The fs module in Node.js is designed to work with the file system on your computer. It allows you to work with files on your server, including creating, reading, updating, deleting, and renaming files.
Including the fs Module
To use the fs module, you need to require it in your application:
const fs = require('fs');
Reading Files
To read the content of a file, use the fs.readFile() function. This function reads the entire file and then calls the callback function with the file content:
fs.readFile('example.txt', 'utf8', function(err, data) {
if (err) throw err;
console.log(data);
});
Writing Files
To write to a file, use the fs.writeFile() function. If the file does not exist, it will be created:
fs.writeFile('example.txt', 'Hello, World!', function(err) {
if (err) throw err;
console.log('File written!');
});
3. Code Examples
Reading a File
const fs = require('fs');
// Read the file
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error('An error occurred:', err);
return;
}
// The file data is a string
console.log('File content:', data);
});
In this code snippet, we read the file example.txt and then log its contents to the console. If an error occurs (for example, if the file does not exist), we log the error message.
Writing a File
const fs = require('fs');
// Write to the file
fs.writeFile('example.txt', 'Hello, World!', (err) => {
if (err) {
console.error('An error occurred:', err);
return;
}
console.log('File written successfully!');
});
In this code snippet, we write the string Hello, World! to the file example.txt. If the file does not exist, it will be created. If an error occurs, we log the error message.
4. Summary
In this tutorial, we learned how to read and write files in Node.js using the fs module. We've covered how to include the fs module in your application and use its readFile() and writeFile() functions to interact with files.
For further learning, explore other fs functions, such as fs.appendFile() to append data to a file, fs.rename() to rename a file, and fs.unlink() to delete a file.
5. Practice Exercises
- Write a Node.js script to create a new text file and write the string "I'm learning Node.js!" to it.
- Write a Node.js script to read the file created in the previous exercise and log its contents to the console.
- Modify the script from exercise 2 to append "And it's fun!" to the file before reading it.
Remember, practice is key to mastering any programming concept. Happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article