DEV Community

Cover image for Get Started With Node.Js
Divine Ikhuoria
Divine Ikhuoria

Posted on

Get Started With Node.Js

TLDR: In this article you will learn how to get started with node.js and use http module to create a server

What's Node.js

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on a JavaScript Engine and executes JavaScript code outside a web browser, which was designed to build scalable network applications.

To access web pages of any web application, you need a web server. The web server will handle all the http requests for the web application e.g IIS is a web server for ASP.NET web applications and Apache is a web server for PHP or Java web applications.

Node.js provides capabilities to create your own web server which will handle HTTP requests asynchronously. You can use IIS or Apache to run Node.js web application but it is recommended to use Node.js web server

Installation

Download Node.js from the official website https://nodejs.org/en/download

When you install node.js node npm and npx will be added to your Environment Variable automatically

Writing your first Node.js Program

Create a folder then type npm init -y to create a packages.json where all your dependencies you install will be saved. Node have some already installed dependencies, and http is part of them.

In your folder create a file named index.js

var http = require('http'); // 1 - Import Node.js core module

var server = http.createServer(function (req, res) {   // 2 - creating server

    //handle incomming requests here..

});

server.listen(5000); //3 - listen for any incoming requests

console.log('Node.js web server at port 5000 is running..')
Enter fullscreen mode Exit fullscreen mode

In the above example, we import the http module using require() function. The http module is a core module of Node.js, so no need to install it using NPM. The next step is to call createServer() method of http and specify callback function with request and response parameter. Finally, call listen() method of server object which was returned from createServer() method with port number, to start listening to incoming requests on port 5000. You can specify any unused port here.

Run the above web server by writing node server.js command in command prompt or terminal window and it will display message as shown below:

$ node server.js
Node.js web server at port 5000 is running...
Enter fullscreen mode Exit fullscreen mode

This is how you create a Node.js web server using simple steps.

Check out my github Divuzki

Top comments (0)