Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a web browser. It is built on Chrome’s V8 JavaScript engine and allows developers to run JavaScript on the server-side, enabling the development of scalable and high-performance network applications. Node.js uses an event-driven, non-blocking I/O model, which makes it lightweight and efficient, suitable for building real-time applications like web servers, chat applications, APIs, and more. Additionally, Node.js has a vast ecosystem of libraries and frameworks available via npm (Node Package Manager), making it a popular choice for developers for building various types of applications.
Advantage of Nodejs
- Open source
- Efficient Fast and highly scalable
- Event Driven
- Very popular
Example:-
Let’s create a simple HTTP server using Node.js. This server will listen for incoming HTTP requests and respond with a basic “Hello, World!” message.
// Import the 'http' module
const http = require('http');
// Define the hostname and port number
const hostname = '127.0.0.1';
const port = 3000;
// Create a server
const server = http.createServer((req, res) => {
// Set the response header
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send the response body (Hello, World!)
res.end('Hello, World!\n');
});
// Start the server and make it listen on the specified hostname and port
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
In this example:
- We import the built-in
http
module, which allows us to create an HTTP server. - We define the hostname and port number on which our server will listen for incoming requests.
- We create an HTTP server using the
http.createServer()
method. This method takes a callback function that will be called whenever a request is received by the server. - Inside the callback function, we set the response header using
res.writeHead()
and send the response body withres.end()
. - Finally, we start the server by calling
server.listen()
and passing it the port, hostname, and a callback function to be executed once the server starts.
When you run this Node.js script, it will start an HTTP server on http://localhost:3000/
. If you visit this URL in a web browser or make a request using tools like cURL or Postman, you’ll receive the response “Hello, World!” from the server.