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.