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:
fs
module in your Node.js applicationfs
modulefs
modulePrerequisites: Basic understanding of JavaScript and Node.js.
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.
fs
ModuleTo use the fs
module, you need to require it in your application:
const fs = require('fs');
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);
});
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!');
});
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.
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.
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.
Remember, practice is key to mastering any programming concept. Happy coding!