3.4. NodeJS Basics: Creating an HTTP Server
NodeJS is a software development platform that allows developers to create efficient and scalable networking applications. It utilizes JavaScript, a popular and widely used programming language, and allows code to run on the server rather than the client's browser. This allows developers to create complex network applications that can handle multiple simultaneous connections and manage large amounts of data.
One of the most fundamental concepts in NodeJS is the creation of an HTTP server. An HTTP server is software that accepts HTTP requests from clients, which are usually browsers, and serves them HTTP responses along with optional data, which is usually web pages, images, or other files.
To create an HTTP server in NodeJS, you need the built-in HTTP module. The HTTP module allows NodeJS to transfer data over the Internet. To include the HTTP module, use the require('http')
.
var http = require('http');
Once you include the HTTP module, you can use the createServer()
method to create an HTTP server. The createServer()
method returns an object that you can use to respond to HTTP requests. This object has a method called listen()
, which you can use to specify which port the server should listen on.
var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Hello World!'); }).listen(8080);
In this example, the HTTP server is configured to respond with "Hello World!" for any order. The function passed to the createServer()
method is called a callback function, and is called whenever someone tries to access the server.
The response object, res
, is used to send data back to the client. The writeHead()
method is used to send an HTTP status code (200 means success) and to define the content type of the response. The end()
method is used to end the response and send the data back to the client.
The listen()
method causes the server to "listen" on port 8080. This means that the server is running and listening for requests on port 8080. You can use any port number you like. you want, but ports below 1024 are reserved for well-known services (eg port 80 for HTTP, port 443 for HTTPS).
To test the server, you can open a browser and type http://localhost:8080
in the address bar. You should see the message "Hello World!".
Creating an HTTP server is just the first step in creating web applications with NodeJS. Once you have a server running, you can start building your application logic, handling different types of requests and responses, working with databases, and much more.
In summary, NodeJS is a powerful tool for developing web applications. With a solid understanding of basic concepts, such as creating an HTTP server, you can start building complex and efficient applications.