Reading and writing files in Node Node.js

  • Post category:Node
  • Reading time:2 mins read

In this post, we will learn how to read a file and write something to a file in Node.js using the file system module. Before we start, let’s see how to run a simple program in node.js

How to read and write files in Node

In the above image, you can see I created a variable myName with the ‘Abhishek’ value. Now, to get this output in the node terminal, we can write node, then space and name of the file.

For example: node file1.js

You can see the printed value in the terminal.

Reading and writing files in Node

Now, let’s see how we can read and write a file in node.js

Reading a file in node.js

how to read a txt file in node.js

Let’s understand the above code.

In this code, I used FS, which stands for file system. I used ‘require’ to use the file system in the code. FS is basically used for reading and writing files in node.

Writing a file in node.js

To write anything in a file, we can use writeFileSync.

how to write in a file in nodeIn the above code, I have written the text ‘we are learning node.js’ in file3.txt. WriteFileSync will write this text in file3.txt. In line number 5, I used ${getText} to get the file2.txt text data in the file3.txt.

Now, when I open file3.txt, it will show the line number 5 text, and after – it will show the text of file2.txt because I have stored the file2.txt value in the getText variable. See the screenshot below.

creating a file in node

Share this