![nodejs write to file nodejs write to file](https://www.c-sharpcorner.com/UploadFile/BlogImages/06152016002557AM/image003.jpg)
This readFilySync()` function will return the file that we have mentioned. Here, we import the fs module from NodeJS built-in module and then read a file that is located in the same directory in the text folder with the name of readfile.txt.
NODEJS WRITE TO FILE CODE
Let’s see the below code example: const fs = require('fs')Ĭonst textRead = fs.readFileSync('./text/readfile.txt','utf-8') If you don’t use the character encoding then the output will be shown as a buffer. It takes two arguments, the first one is the path of the particular file that will be read and the next one is the character encoding. We already know about the fs module and this module helps us to read a file synchronously. In this section, we will read a file synchronously, and to do so we will use fs.readFileSync() function. We will import this module to work with the file system and read and write our file. It will require the module from NodeJS built-in module and is available for you to use it.
![nodejs write to file nodejs write to file](https://parallelcodes.com/wp-content/uploads/2021/03/node-js-file-append-example-002.png)
Here, we have used const instead of using var and it is an ES6 feature. Let’s see the below code example of how you can import the fs module in your project. It will work both in a synchronous and asynchronous way. such as read file, write file, append file, and so on. The meaning of fs is a file system that helps you to work with files. NodeJS lets you perform different useful actions with its built-in modules.