Node JS Tutorial - Reading & Writing Files
In this tutorial, we will learn about reading and writing files on our local filesystem using Node.js. To achieve this, we will use the fs package.
Reading Data from a File
Let's see how we can read data from a file. Go to the project and create a text file named message.txt. Inside the message.txt file, type a message:
This is a text message from file.
Now, go to the index.js file and require the fs package:
var fs = require("fs");
fs.readFile("message.txt", "utf-8", function(err, data) {
console.log(data.toString());
});
Let's check it. Go to the command prompt and run the command:
node index.js
Now, you can see the text message from the file.
Error Handling
If you want to catch errors, such as the file you are trying to reach not being found, you can do so like this:
fs.readFile("not-found.txt", "utf-8", (err, data) => {
if(err){
console.log(err)
}
console.log(data);
})
Now, let's change the file to one that does not exist and check. Re-run the index.js file. You can see the error message.
Writing Text to a File
Now, let's see how we can write text to a file:
var fs = require("fs");
var data = "New File Contents";
fs.writeFile("temp.txt", data, (err) => {
if (err) console.log(err);
console.log("Successfully Written to File.");
});
Let's re-run the index.js file:
node index.js
You can see that the text has been successfully written to the file. Let's check the file, and you can see the text inside the message.txt file.
In this way, you can read and write files in Node.js, allowing you to interact with your local filesystem.