File Operations in Node.js:
Reading and Writing Files Synchronously
This blog post explores how to read and write files synchronously in Node.js using the File System module. It covers the necessary steps to import the module, read from a text file, and write to a new file, highlighting the synchronous nature of these operations and their implications on application performance.
Understanding the File System Module
To begin working with files in Node.js, we need to import the File System module. This module provides various methods for file operations. We will refer to this module as fs for convenience.
Importing the File System Module
At the top of your JavaScript file, you should include the following code to import the fs module:
const fs = require('fs');
This statement imports the fs module and assigns it to the variable fs, allowing us to access its methods.
Reading Files Synchronously
To read a file synchronously, we will use the readFileSync method provided by the fs module. Here’s how to do it:
Step 1: Create a Sample Text File
First, create a folder named files within your project directory. Inside this folder, create a text file named input.txt and add some sample text:
This is a sample text file which we are going to read using Node.js.
Step 2: Read the File
Now, we can read the contents of input.txt using the following code:
const text = fs.readFileSync('./files/input.txt', 'utf-8');
console.log(text);
In this code:
We specify the relative path to
input.txt.We use
utf-8as the encoding to read the file correctly.The content of the file is stored in the variable
text, which we then log to the console.
Step 3: Running the Code
To execute your code, run the following command in your terminal:
node app.js
You should see the content of input.txt printed in the console. It’s important to note that readFileSync reads the file synchronously, meaning that if the file is large and takes time to read, the execution of the next line of code will be blocked until the reading is complete.
Writing Files Synchronously
Next, we will explore how to write to a file using the writeFileSync method.
Step 1: Create an Output File
In the same files folder, create a new file named output.txt. We will write content to this file.
Step 2: Write to the File
To write to output.txt, use the following code:
const content = `Data read from input.txt: ${text}\nDate created: ${new Date()}`;
fs.writeFileSync('./files/output.txt', content);
In this code:
We create a string
contentthat includes the data read frominput.txtand the current date and time.We then use
writeFileSyncto write this content tooutput.txt.
Step 3: Running the Code Again
After saving your changes, run the command:
node app.js
If output.txt already exists, it will be overwritten with the new content. If it does not exist, Node.js will create the file and then write the content to it.