DEV Community

Cover image for File handling 101 in Node Js
Abhishek Kumar
Abhishek Kumar

Posted on

File handling 101 in Node Js

if you have ever worked with programming languages like C++, Python or Java then you might have come across a term called "File handling". But If you are a Javascript Developer (which I assume if you are reading this blog), you might not have come across anything as such because there isn't support for File handling in Js. But what if there was a way to use Javascript code to perform file handling? Don't worry Node js has come to your rescue. Let's find out how

Before moving forward we have to understand a few things like what is node js, how node js works & what is asynchronous and synchronous code . Having an understanding of these will help you not only with file handling but in general while working with node js as a backend developer.

What is Node Js? And why is it important?

Node Js is a Runtime environment for javascript.

A runtime environment is a software framework that provides a platform for executing and running applications. It includes libraries, tools, and resources necessary for the execution of code written in a specific programming language.

So what does this mean to you and me who are a javascript developer? Well, it means a lot. Earlier Developers used to write code in a file (index.js) and use a browser to execute our code. Because In those days Only browsers had a runtime environment to execute js code. Javascript was meant to be a scripting language for the Web and that too in the Front-end part.

vanilla js

But now With Node Js, you can run JS code in your local system and perform a lot of tasks. Also with Node js, you can write frontend as well as backend code using MERN (MongoDB, Express, React, Node) or MEAN (MongoDB, Express, Angular, Node). In simple terms, You can Become a full-stack developer using JS only (obviously there are a lot of things like HTML, CSS, database and a hell lot of things).

node js

How to Install Node JS?

  • To install Node, go to the Node js official site

  • Click on the 18.16.1 LTS version. It will automatically detect the OS you are using and give suggestions based on that

  • Install just like you install any other software keeping everything as default.

  • To check if Node is properly installed on your system or not, Open the terminal/command prompt and type: node -v. If you see the node version written there that means Node is properly installed on your system.

  • Now you can Write any js code Except the DOM manipulation as it is for browsers. Open the command prompt and type console.log("Hello,World")

You Have successfully executed your first node command(I know it's Js only ). Now that we have understood Node .let's understand Async and Sync code flow and why is it important in file handling.

Async vs Sync code flow

In Node.js, asynchronous (async) and synchronous (sync) operations refer to different approaches for executing code and handling I/O operations

  • Synchronous: This type of code in Node.js block the execution of the program until the operation is completed. It means that each operation will have to wait for the previous one to finish before moving on to the next line of code. Here's an example of synchronous file reading in Node.js:
const fs = require('fs');
// Synchronous file reading
try {
  const data = fs.readFileSync('test file.txt', 'utf8');
  console.log(data);
} catch (err) {
  console.error(err);
}

Enter fullscreen mode Exit fullscreen mode
  • Asynchronous: It is completely opposite to sync operation. It does not block the program. It allows the program to continue its execution while the operation is being processed in the background . Async in file handling needs a callback function.
const fs = require('fs');
// Asynchronous file reading with callback
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) {
    console.error(err);
  } else {
    console.log(data);
  }
});
Enter fullscreen mode Exit fullscreen mode

Now that we have understood the prerequisites of File handling with Node js. let's go straight to it.

File Handling in Node JS: Reading and Writing Files in Node.

File handling in the node is possible due to a module called fs (file system). It provides all the necessary methods and functions to perform various operations, such as reading, writing, copying, updating, and deleting files.

we will see the syntax of this and will discuss various methods one by one. Below is an example of the sync readFile method. we will see this in detail but for now, let's understand the syntax of this.

const fs = require('fs');
// Synchronous file reading

  const data = fs.readFileSync('file.txt', 'utf8');
  console.log(data);
Enter fullscreen mode Exit fullscreen mode

What are we doing here:

  • The code imports the built-in fs module, which provides file system-related functionality in Node.js.

  • The readFileSync a function is called to read the contents of the file named "file.txt".

  • If the file reading operation is successful, the returned data is assigned to the data variable.

  • The contents of the file are then logged to the console using console.log(data)

Writing in files: Both Async and Sync operations

Writing Files in sync flow: We can read files by using the fs module's writeFileSync

you can easily retrieve the contents of a file and process them according to your needs. let us see the code implementation of this. As writeFileSync a sync operation it requires two parameters, one is a file name with the proper file extension. For example, if it is a text file so the name will be text.txt and next is the contents of the file.

fs.writeFileSync("./test.txt", "this is sync")   //sync writeFile op
Enter fullscreen mode Exit fullscreen mode

As soon as you type node filename.js in the terminal, it will create a test.txt file in your directory with the content that you have passed. In this case, is "this is sync". Remember this is a sync operation so it will block the other operations, so try to avoid using it.

  • Writing File in Async flow: In the async example, the WriteFile function initiates the file writing operation and immediately moves on to the next line of code without waiting for the operation to complete. Once the operation finishes, the callback function is invoked with the result or an error.

Note: this is an async operation so a callback function is necessary. Async operations are generally preferred in Node.js for I/O-intensive tasks since they allow the program to remain responsive and handle multiple requests simultaneously.

Reading File in sync way: This will have two params, One is a file name.txt and second is encoding (utf 8 for string )

const readFile = fs.readFileSync("./test.txt", "utf8");
console.log(readFile)   //log the content of test.txt file
Enter fullscreen mode Exit fullscreen mode
  • Reading File in async way: In this, it will have 3 params, filename, encoding, and callback function with two params which include error and data(you can call it anything) error will used to log if there is any error while reading the file and data is used to log the content of the file.
 fs.readFile("./test.txt", "utf8", (err, data) => {
   if (err) console.log("Error :", err);  //log if any err found
  console.log(data);  //log the content in test file
 });
Enter fullscreen mode Exit fullscreen mode
  • Appending the file: Let's suppose you want to add some more content in the file but when you use the method discussed above it will over-write anything in it and add the new content in it. But we want to keep both of them so what should we do? There comes the append method which lets us add new content without overwriting the previous content.

  • Synchronous File appending:

const fs = require('fs');
// Synchronous file appending
fs.appendFileSync('file.txt', 'New data to append', 'utf8');
Enter fullscreen mode Exit fullscreen mode
  • Async Append:
const fs = require('fs');
// Asynchronous file appending
fs.appendFile('file.txt', 'New data to append', 'utf8', (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('Data has been appended to the file successfully.');
  }
});
Enter fullscreen mode Exit fullscreen mode

Ok so now that we have basic knowledge of how to read, write, and append files in both async and sync way and which way is best. We are good to go and explore file handling in node js.

Conclusion: File handling in Node JS

Congratulations! You've learned the fundamentals of file handling in Node.js. with the knowledge of the fs modules, you can confidently perform a variety of file operations, read and write data, and append data. By mastering file handling in Node.js, you'll unlock new possibilities for building robust web applications.

This was my attempt to tell you about File handling in node js. I hope you have learnt something today. I write content related to Web Development so if this is your area of interest then you can subscribe to me. I will try my level best to bring more such content in future.

If you are someone looking for a tech writer who can write content about Web Development, You can check my other blogs here . I am available to write content related to this topic.

Conclusion on node js

Connect with me on various Socials:

Linkedin: where I share things I am learning and building

Twitter: I share my mind, and threads related to web dev daily. follow for valuable content there also.

Check out my GitHub, and the projects I am working on. I am a open source contributor also.

Top comments (0)