Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to run JavaScript on the server side. Built on Chrome's V8 JavaScript engine, Node.js is designed to build scalable, fast, and real-time applications.
Why Choose Node.js?
Let’s build a simple Node.js server that listens for requests and responds with a "Hello, Node.js!" message.
Install Node.js: Download and install Node.js from its official website.
Create a JavaScript File: Create a file named app.js
.
Write the Code:
// Import the http module
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// Set the response HTTP header
res.writeHead(200, {'Content-Type': 'text/plain'});
// Send a response
res.end('Hello, Node.js!');
});
// Make the server listen on port 3000
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Run the Server: In your terminal, navigate to the folder where your app.js
file is located and run the following command:
node app.js
Access the Server: Open your browser and go to http://localhost:3000. You should see the message "Hello, Node.js!".
Common Use Cases:
This example demonstrates how to create a basic web server with Node.js. It's a great starting point to understand how Node.js handles requests and serves responses.