Working with NodeJs function using asynchronous way

Working with NodeJs 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 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 module. The package.json file will be like the below:



  "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:



<html lang="en">
    <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>
    <h1>This is home page</h1>
    <button onclick="AlertMe()">Click Me</button>

        function AlertMe(){
            alert("You have pressed the button");


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:



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' });


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.