0 votes
177 views
by
Demonstrate the working of Node JS by creating a simple server to display a “Welcome” message

1 Answer

0 votes
by (98.9k points)
 
Best answer

Install Node.js: If you haven't already, you'll need to install Node.js on your computer. You can download it from the official website: https://nodejs.org/

Create a Project Folder: Create a new folder for your Node.js project and navigate to it using your terminal or command prompt.

Initialize a Node.js Project: Open your terminal or command prompt and navigate to your project folder. Then, run the following command to initialize a new Node.js project and create a package.json file:

npm init -y

 

Create a JavaScript File: Create a JavaScript file (e.g., server.js) in your project folder. You can use any code editor to create this file.

Write the Node.js Code: Open server.js and write the following code to create a simple HTTP server:

// Import the 'http' module
const http = require('http');

// Create an HTTP server
const server = http.createServer((req, res) => {
  // Set the response header with a 200 OK status and plain text content type
  res.writeHead(200, { 'Content-Type': 'text/plain' });

  // Send the "Welcome" message as the response
  res.end('Welcome to my Node.js server!\n');
});

// Listen on port 3000
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

 

Start the Server: In your terminal, run the following command to start the Node.js server:

node server.js

You should see the message "Server is running on port 3000" in your terminal, indicating that the server is up and running.

Access the Server: Open your web browser and navigate to http://localhost:3000/. You should see the "Welcome to my Node.js server!" message displayed in your browser.

Related questions

0 votes
1 answer 46 views
0 votes
0 answers 32 views
0 votes
0 answers 31 views
+1 vote
1 answer 62 views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

506 users

...