Bytes

Your first Node JS application

Last Updated: 22nd June, 2023

Introduction

The goal of the lesson is to teach the learner how to create a simple Node.js application from scratch. This will involve guiding the learner through the process of creating a basic Node.js application using JavaScript and understanding the fundamental concepts and best practices of Node.js development.

The lesson may cover topics such as creating a Node.js project using a package manager like npm, writing JavaScript code to define and implement the functionality of the application, and using Node.js modules and libraries to extend the capabilities of the application.

The ultimate objective of the lesson is to equip the learner with the foundational knowledge and skills needed to create a basic Node.js application on their own and to provide them with a starting point for further exploration and experimentation with Node.js development.

Prerequisites

Here are some prerequisites for a beginner to create the first Node.js application:

  1. Basic knowledge of JavaScript: Node.js is a JavaScript runtime, so it is essential to have a basic understanding of JavaScript, including data types, variables, functions, loops, and conditional statements.
  2. Command line basics: As you will be running your Node.js application from the command line, it is necessary to have some knowledge of command-line basics, such as navigating directories, creating and deleting files and directories, and running commands.
  3. Node.js installation: You will need to install Node.js on your computer. You can download the installer from the official Node.js website and follow the installation instructions.
  4. Text Editor: You will need a text editor to write your Node.js code. There are several options available, including Visual Studio Code, Atom, Sublime Text, etc. Choose the one that suits you the best.
  5. Node Package Manager (NPM): NPM is a package manager that comes with Node.js, allowing you to install and manage external modules easily. You will need to have some understanding of NPM to install and use external modules in your Node.js application.

By having a good grasp of these prerequisites, you can get started with creating your first Node.js application.

Creating a new project

We can create a new project in either mentioned ways below that are using CLI or without using CLI.

Using CLI (Command Line Interface)

Here are the basic steps to create a new project in Node.js:

  1. Install Node.js: If you haven't already, download and install Node.js from the official website.
  2. Create a new project directory: Create a new directory for your project using the command line interface (CLI). For example, you can use the following command:
mkdir myproject
  1. Initialize a new Node.js project: Navigate to the project directory you just created and use the following command to initialize a new Node.js project:
cd myproject
npm init

This will create a package.json file that describes your project and its dependencies.

Without Using CLI

  1. Create a new folder: Right click → New → Folder name(myproject)→ enter.
  2. Open this folder in any text editor like VScode, Atom, Sublime, etc.
  3. The next step is to create our file to write code which we will see further.

Congratulations, you have created a new project in Node.js!

Writing an application code

Now let's proceed to write our application code and make our first Node.js application.

  1. Open the folder you created in any text editor of your choice. Here, we will be taking the reference of Visual Studio Code.
  2. Create a new file ‘index.js’ under your project folder in Visual Studio Code.
  3. Open the index.js file with your preferred text editor and start adding your Node.js code.
const http = require('http');

The statement const http = require('http');loads the httpmodule and assigns it to the httpconstant. This allows you to use the functions and objects provided by the httpmodule in your code.

  1. After this, add the below code lines
const server=http.createServer((req,res)=>{
    res.write('Hello World!')
    res.end()
})

Here is what is happening in the above code step by step

The createServermethod takes a callback function as its argument, which is executed every time the server receives an HTTP request. The callback function takes two parameters, req**,** and res, which represent the incoming HTTP request and the server's response, respectively.

In the callback function, the res.write()method is called to write the "Hello World!" message to the response.

The res.end()method is called to end the response and send it back to the client.

So, when the code is executed and the server is running, if a client sends an HTTP request to the server, the server will respond with the "Hello World!" message.

Finally, add these lines below to complete the first application.

server.listen(3000, () => {
    console.log('Server running on port 3000');
  });

Here's what's happening in the above code:

  1. The listenmethod of the serverobject is called with two arguments: the first argument is the port number (3000in this case) that the server should listen on, and the second argument is a callback function that will be executed when the server starts listening on the specified port.
  2. In the callback function, the message "Server running on port 3000" is printed to the console using the console.logmethod.

So, when the code is executed and the server starts listening on port 3000, the message "Server running on port 3000" will be printed to the console. This indicates that the server is ready to receive incoming HTTP requests on port 3000.

Running the application

Now our application is ready to run successfully. Our ‘Index.js’ file should look like this below. Comments are also attached to make the code more readable and easy to understand.

// Loads the module
const http = require('http');  

const server=http.createServer((req,res)=>{
    // Text to the body
    res.write('Hello World!')   

    // Telling server that all header and body response has been sent 
    res.end()                   
})

// Defining port for the server to run
server.listen(3000, () => {                       

    //Message to print on the console after a successful run
    console.log('Server running on port 3000');   
  });

To run the file open a terminal on your editor and type the following command

node index

The console of the text editor must show the message ‘Server running on port 3000

To check if the server is actually running or not, navigate to your browser, and on the address bar/URL bar type the below line and hit enter.

localhost:3000

You can see on hitting enter it shows the message ‘hello world’ like this below.

You have run your first application successfully!

Conclusion

We learned how to create a simple HTTP server using the built-in http module, and how to respond to incoming HTTP requests with a "Hello World!" message. We also saw how to start the server and listen for incoming requests on a specific port.

Creating a simple Node.js application like this one is just the tip of the iceberg when it comes to what you can do with Node.js. With its powerful set of libraries and tools, Node.js can be used to build a wide range of web applications, including real-time chat applications, streaming services, and more.

By learning Node.js, you can add an incredibly versatile and in-demand skillset to your development toolkit. As you continue to explore Node.js and its many capabilities, you'll find that the possibilities for building innovative and powerful web applications are virtually endless.

Module 1: Getting Started with Node JSYour first Node JS application

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter