2024-06-05 . 1 min(s)
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows you to run JavaScript on the server, enabling you to build scalable network applications.
To get started, you need to install Node.js. You can download it from the official website and follow the installation instructions for your operating system.
With Node.js installed, you can create a simple server using the built-in http
module.
Example:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
To run the server, save the code to a file (e.g., server.js
) and execute it with Node.js:
node server.js
You should see the message "Server running at http://127.0.0.1:3000/" in your terminal. Open your browser and navigate to http://127.0.0.1:3000/
to see the "Hello, World!" message.
Express.js is a popular web framework for Node.js, making it easier to build web applications and APIs.
Example:
const express = require('express');
To use Express.js, you need to install it first:
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
npm install express
Express.js simplifies routing and handling HTTP requests, allowing you to build robust web applications quickly.