How to create a text file with NodeJs.

In this article, i will show you how to create a text file with NodeJs. Before we get started, i hope you understand my article on how to Get Start With NodeJs by a simple hello.

After understanding a basic JavaScript and a basic NodeJs you will able to create text file with NodeJs in just a simple line of code such as written bellow;

const fs = require('fs');

fs.writeFileSync('hello.text','Hello from Sifi!');

There it is, a simple line of code can create a file called ‘hello.txt’. With a pass in parameter ‘Hello from Sifi!’. Let me explain to you how this work,on the first line of code such as const, that is a short name for constant. A constant stores whatever you want to store which in our case we named the const as fs, a short name for file system. Than you need to declare fs with ‘ = ‘ for the function we want to use which in our case we want to use file system to create a text. If you read NodeJs library fs is a function of file system that also has other functions.

After accessing fs, we can simply use the function that NodeJs provides and pass in the parameter that we need. The first parameter is obviously a text file which we wanted to create and the second parameter is what text function we want it to write inside our text file.

Now its time to run it on our local IDE and test it out. As you can see from the image below, We are able to create a hello.txt file as we intended:

Leave a Reply