support@codebucket.net

Working with NodeJs fs.read() function using asynchronous way

Working with NodeJs fs.read() function using asynchronous way

K. M. Shawkat Zamil | September 26, 2022

Hello Developers,

In this tutorial, I will show you how to deal with the NodeJs fs.read() module. First, you need to create a server using the HTTP module. (NodeJs Server Related Tutorial)

 

If you are new at NodeJs development, this demonstration is for you. First, you need to initialize the node using the below command in a directory:

 

npm init --y

 

Then package.json will be created in the directory. Now we need to create the index.js file and an HTML file to use the fs.read() module. The package.json file will be like the below:

 

/package.json

{
  "name": "fsmodule",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

 

In our HTML file, there will be a button only. The HTML file will be like the below:

 

/home.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>
</head>
<body>
    <h1>This is home page</h1>
    <button onclick="AlertMe()">Click Me</button>


    <script>
        function AlertMe(){
            alert("You have pressed the button");
        }
    </script>
</body>
</html>

 

In our index.js file, first, we created a server and we have to call the fs module to work with File System. When we hit the main route the fs.readFile() read the HTML file and the call back function will deal with the data. The button click event will capture in the response.write() method. With the help of the server.listen command the webpage will run. The index.js file code is given below:

 

/index.js

var fs = require('fs');

var http = require('http');

var server = http.createServer(function (request, response) {

    if (request.url = '/') {
        
        //Asynchronous File Read
        fs.readFile('home.html', function (error, data) { 
            response.writeHead(200, { 'content-Type': 'text/html' });
            response.write(data);
            response.end();
        });
    }

});

server.listen('5000');
console.log('Server Running Successfully');

 

Now run npm start in the terminal.

 

npm start

 

Hope this might help you in the development journey. 

 

Read More: How to run Hello World in Node Server

 

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.