Creating a Node.js server

Node.jsServer Side ProgrammingProgramming

The mostly used core modules of Node.js are −

  • http − used to launch a simple server, send requests

  • https − used to launch a ssl secured http server

  • path − used to handle path based on operating system

  • fs − It’s a file system handling module

  • os − its used for os related operations

Lets build a simple http server using Node.js −

Create a javascript file App.js (name it as you like) in an editor like visual studio code .

App.js

const http = require(‘http’);
function reqListener(req, res){
   console.log(‘Hello’);
}
const server = http.createServer(reqListener);
server.listen(3000);

Explaination

We used const keyword instead of var or let to import a module because this variable reference will not changed in file.

Require is a reserved keyword in Node, it helps to import pre-defined core modules and used defined modules.

Importing pre-defined modules like http does not require to add ./ in front of them. But if requires to import a custom used defined module then it is done as shown below −

const user = require(‘./User’);

Adding .js extenstion to file in require function is not mandatory for javascript file. But any other file formats will require to add an extension in require function.

The imported module http has a createServer method which takes request listener as an parameter. This argument function will be executed on every new http request to Node server.

We can use anonymous function or a next-gen javascript arrow function as well in createServer method −

Anonymous function in createServer

const http = require(‘http’);
const server = http.createServer(function(){
   console.log(‘Hello’);
});
server.listen(3000);

Using next-gen Javascript

const http = require(‘http’);
const server = http.createServer((req, res)=>{
   console.log(‘Hello’);
});
server.listen(3000);

createServer method of http module returns us a server. We can use a listen method on server to run it on a given port. listen method takes port number as an argument.

Executing App.js file

Open terminal inside folder where App.js is located and run command − node App.js

Running this command will keep a event loop running listening for any http request on port 3000.

Checking console log messages on terminal

Now, open a browser and navigate to localhost:3000, check in terminal console for a log statement. On console of terminal we will see Hello message printed.

As of now, we have not returned any response back to browser, so we wont see any output on it. We will see how to return and display response messages on browser in next articles.

raja
Published on 13-May-2020 11:14:33
Advertisements