node.js example
- User
node.js example
- Assistant
Certainly! Below you'll find an example of a simple Node.js application that sets up a basic web server using the built-in
httpmodule.-
Initialization: First, ensure you have Node.js installed. You can download it from nodejs.org.
-
Create the server:
Here's a basic example showing how to create a server:
// Load the http module to create an HTTP server. const http = require('http'); // Configure the HTTP server to respond with "Hello, World!" to all requests. const server = http.createServer((req, res) => { // Set the HTTP response header with HTTP status and Content type res.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as "Hello, World!" res.end('Hello, World!\n'); }); // Listen on port 3000, IP defaults to 127.0.0.1 server.listen(3000, '127.0.0.1', () => { console.log('Node.js server is running at http://127.0.0.1:3000/'); });- Run the server:
Save the code to a file named
server.jsand run it using Node.js:node server.js- Access the server:
Open a web browser and navigate to
http://127.0.0.1:3000/. You should see "Hello, World!" displayed on the page.
Advanced Example with Express.js
For more advanced web applications, developers often use frameworks like Express.js. Here's how to set up a basic server using Express:
Install Express
First, create a new directory for your project and initialize a new Node.js project:
mkdir myapp cd myapp npm init -yThen, install Express:
npm install expressCreate a server with Express
Create a file named
app.jsand add the following code:const express = require('express'); const app = express(); const port = 3000; // Define a route for the root path app.get('/', (req, res) => { res.send('Hello, World!'); }); // Start the server and listen on port 3000 app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); });Run the server
Start your server by running:
node app.jsAccess the server
Open a web browser and navigate to
http://localhost:3000/. You should see "Hello, World!" displayed on the page.This Express example provides a more scalable and flexible way to build web applications compared to using the built-in
httpmodule. -