0% found this document useful (0 votes)
7 views3 pages

Create a Node.js Web Server Guide

Cyber

Uploaded by

Ganesh Hasnale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

Create a Node.js Web Server Guide

Cyber

Uploaded by

Ganesh Hasnale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

4-Web Server

4.1 Creating web server


4.2 Handling http requests
4.3 Sending requests

Introduction: 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 [Link] web applications
and Apache is a web server for PHP or Java web applications.
[Link] provides capabilities to create your own web server which will handle HTTP requests
asynchronously. You can use IIS or Apache to run [Link] web application but it is recommended to use
[Link] web server.

Create [Link] Web Server : [Link] makes it easy to create a simple web server that processes incoming
requests asynchronously.

var http = require('http'); // 1 - Import [Link] core module

var server = [Link](function (req, res) { // 2 - creating server

//handle incomming requests here..

});

[Link](5000); //3 - listen for any incoming requests

[Link]('[Link] web server at port 5000 is running..')

In the above example, we import the http module using require() function. The http module is a core module
of [Link], 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 [Link] command in command prompt or terminal window and
it will display message as shown below.

C:\> node [Link]


[Link] web server at port 5000 is running..

This is how you create a [Link] web server using simple steps. Now, let's see how to handle HTTP request
and send response in [Link] web server.

Handle HTTP Request


The [Link]() method includes request and response parameters which is supplied by [Link]. The
request object can be used to get information about the current HTTP request e.g., url, request header, and
data. The response object can be used to send a response for a current HTTP request.
The following example demonstrates handling HTTP request and response in [Link].
var http = require('http'); // Import [Link] core module

var server = [Link](function (req, res) { //create web server


if ([Link] == '/') { //check the URL of the current request
// set response header
[Link](200, { 'Content-Type': 'text/html' });

// set response content


[Link]('<html><body><p>This is home Page.</p></body></html>');
[Link]();

}
else if ([Link] == "/student") {

[Link](200, { 'Content-Type': 'text/html' });


[Link]('<html><body><p>This is student Page.</p></body></html>');
[Link]();

}
else if ([Link] == "/admin") {

[Link](200, { 'Content-Type': 'text/html' });


[Link]('<html><body><p>This is admin Page.</p></body></html>');
[Link]();

}
else
[Link]('Invalid Request!');

});

[Link](5000); //6 - listen for any incoming requests

[Link]('[Link] web server at port 5000 is running..')


In the above example, [Link] is used to check the url of the current request and based on that it sends the
response. To send a response, first it sets the response header using writeHead() method and then writes a
string as a response body using write() method. Finally, [Link] web server sends the response using end()
method.

Now, run the above web server as shown below.

C:\> node [Link]


[Link] web server at port 5000 is running..

To test it, you can use the command-line program curl, which most Mac and Linux machines have
pre-installed.

curl -i [Link]

You should see the following response.

HTTP/1.1 200 OK
Content-Type: text/plain
Date: Tue, 8 Sep 2015 03:05:08 GMT
Connection: keep-alive
This is home page.
For Windows users, point your browser to [Link] and see the following result.

[Link] Web Server Response

The same way, point your browser to [Link] and see the following result.

[Link] Web Server Response

It will display "Invalid Request" for all requests other than the above URLs.

Common questions

Powered by AI

Handling various endpoint requests directly in the `createServer` callback allows the server to dynamically respond with specific content based on the URL path, centralizing request routing within one function. This can simplify development by making the request-handling logic transparent and straightforward, as well as facilitating changes by keeping all the URL-specific logic contained rather than dispersed across multiple scripts or applications . This approach can be efficient for simple APIs or applications where performance impact from this central handling is minimal .

The `createServer` method in Node.js instantiates a new HTTP server that can listen to incoming requests on a specified port. The method takes a callback function as its parameter, which defines the handling logic for 'request' and 'response' objects associated with each incoming HTTP request. This allows the developer to define specific behaviors for different URLs, managing how the server responds to clients . The callback function is crucial for defining custom logic for the webpage content served based on the request URL .

In Node.js, the `writeHead` method is used to set the status code and HTTP headers that will be sent in the response. This is crucial for defining the type of content returned or the state of the request processing, like indicating success with a 200 status code. Following this, the `write` method sends the body's content of the response, such as HTML or JSON data. Finally, `res.end()` finalizes the response sending process, optionally sending ending text .

Listening on port 5000 is typically used for development environments since it avoids conflicts with other services that may use more common ports such as 80 or 443. For a production environment, one might change this to port 80 for HTTP or 443 for HTTPS to make the server publicly accessible without needing to specify a port in the URL . Additionally, a reverse proxy like NGINX or Apache might be used to route requests on standard ports to the Node.js application for improved security, load balancing, and SSL capabilities, while Node.js itself might continue to run on a non-standard port internally .

Node.js provides asynchronous processing capabilities that enable it to handle a larger number of simultaneous requests than traditional synchronous servers like IIS or Apache. This non-blocking, event-driven architecture can lead to improved efficiency and performance, especially for I/O heavy web applications . Additionally, being a JavaScript runtime, Node.js allows developers to use the same language for both client-side and server-side code, potentially simplifying development and reducing context switching between different programming languages .

Node.js web server handles HTTP requests asynchronously by using callbacks. When a request is received, the server processes it without blocking the execution thread, allowing the server to handle other requests concurrently. The createServer function provides a callback that gets executed whenever a request is received. The server continues listening for other incoming requests while responding to previous ones .

The `console.log` statement outputs a message to the terminal whenever the server starts listening, providing immediate feedback about the server's operational status. This can be crucial for development and debugging as it confirms that the server script has been executed successfully and is actively listening for requests on the specified port . It helps identify when the server starts and can aid in locating where the code execution has reached during the script's run-time .

Using a single-threaded model in Node.js can lead to limitations, particularly with CPU-bound operations or when requests involve complex computations, as they can block the event loop and prevent the server from handling concurrent requests efficiently. Unlike multi-threaded architectures like those used in Java's Servlet containers, where different threads can handle separate requests, Node.js relies on event-driven callbacks which may handle high I/O concurrency well but can struggle with processor-intensive tasks . For applications requiring heavy computation, strategies like worker threads or external services may be needed to offload tasks .

Tools like `curl` can be used to manually test Node.js web server responses by sending HTTP requests to specific endpoints and analyzing server replies, including response codes, headers, and body content . For more comprehensive testing, tools like Postman provide a GUI for constructing requests, allowing for automation of tests, and tracking of response times, status codes, and data validation. Tools like Apache JMeter can stress-test scenarios, providing insights into performance under load, concurrency handling, and identifying bottlenecks in the server's response time and throughput .

The `http` module in Node.js is essential for creating HTTP servers, handling all details necessary to facilitate web communication such as incoming requests and sending responses. It is considered a core module because it is built into Node.js, requiring no additional installations or packages, thus facilitating lightweight server creation with just basic Node.js installation . The core status indicates its foundational role and the stability provided to developers in terms of performance and compatibility .

You might also like