Get in touch
or send us a question?

[Node.js Tutorials for Beginners] – Unit 8: Read and write file with module fs in Node.js


Table of Contents

1. What module fs?

2. Read file with module fs

3. Write file with module js

1. What module fs?

Module fs (short for file system) is a module built in node.js that handles files, folders in node.js


var fs = require(‘fs’);

2. Read file with module fs


readFile(‘pathFile’, [option], function(err, data){




+ pathFile is the path of the file to be read.

+ option: can be a string or an array containing the option to encode or mode the file, if no configuration is needed, everyone can leave it blank.

+ err: is the variable containing the error if any.

+ data: is data read from the file.


First, let us a js file named hello.html having the following code:

<!DOCTYPE html>



<meta charset=”utf-8″>

<meta http-equiv=”X-UA-Compatible” content=”IE=edge”>


<link rel=”stylesheet” href=””>


<style type=”text/css” media=”screen”>


color: orange;

text-align: center;




<h1>Welcome to My blog!</h1>



Next, we need create a file unit8.js to initialize the server and process the file

var http = require(‘http’);

var fs = require(‘fs’);

http.createServer(function(request, response){

response.writeHead(‘200’, {‘content-type’: ‘text/html’});

fs.readFile(‘hello.html’, ‘utf8’, function(err, data){

if (err) throw err;





Then you run: node unit8.js and will get the following results:

Welcome to My blog!

3. Write file with module js


Following is the syntax of one of the methods to write into a file


fs.writeFile(filename, data[options], callback)

This method will over-write the file if the file already exists. If you want to write into an existing file then you should use another method available.


+ path: This is the string having the file name including path.

+ data: This is the String or Buffer to be written into the file.

+ options: The third parameter is an object which will hold {encoding, mode, flag}. By default, encoding is utf8, mode is octal value 0666, and flag is ‘w’.

+ callback: This is the callback function which gets a single parameter err that returns an error in case of any writing error.


var fs = require(‘fs’);

console.log(“Going to write into existing file”);

fs.writeFile(‘files/hello.txt’, ‘Simply easy learing!’, function(err){

if (err) {

return console.error(err);


console.log(‘Data written successfully!’);

fs.readFile(‘files/hello.txt’, function (err, data){

if (err) {

return console.error(err);


console.log(‘Data of file: ‘ + data.toString());



Now run the unit8.js to see the result:

$ node unit8.js

Verify the output:

Going to write into existing file

Data written successfully!

Data of file: Simply easy learing!

Thank you for reading!