First Node.js Program | Lecture 3
Here are
notes on writing your first Node.js program:
First Node.js Program
Prerequisites:
- Install Node.js:
- Download and install from
the official Node.js website.
- Verify Installation:
- Check the version of
Node.js and npm:
o node -v
o npm -v
Steps to Create Your First Node.js Program:
- Setup a Project:
- Create a new directory for
your project.
o mkdir first-node-app
o cd first-node-app
- Initialize the Project:
- Create a package.json file to manage project
metadata and dependencies.
o npm init -y
- This generates a package.json file with default
settings.
- Write the Program:
- Create a file named app.js in the project directory.
- Open the file in a code
editor and add the following code:
o // Load the built-in HTTP module
o const http = require('http');
o
o // Create a server
o const server = http.createServer((req, res) => {
o res.statusCode = 200; // HTTP status
o res.setHeader('Content-Type',
'text/plain'); // Set response type
o res.end('Hello, Node.js!'); // Send
response
o });
o
o // Start the server
o const PORT = 3000;
o server.listen(PORT, () => {
o console.log(`Server is running at
http://localhost:${PORT}/`);
o });
- Run the Program:
- Execute the app.js file using Node.js:
o node app.js
- Open a web browser and go
to http://localhost:3000. You will see:
o Hello, Node.js!
Code Explanation:
- const http =
require('http');:
- Loads the HTTP module to
create a web server.
- http.createServer():
- Creates an HTTP server that
listens for requests and sends responses.
- res.end('Hello, Node.js!');:
- Sends the response text to
the client.
- server.listen(PORT,
callback):
- Starts the server and
listens on the specified port.
Enhancements:
- Using Console Logs:
- Add logs to debug or
confirm the server's actions.
o console.log('Request received at', new Date());
- Serving HTML:
- Modify the response to
serve HTML:
o res.setHeader('Content-Type', 'text/html');
o res.end('<h1>Welcome to
Node.js!</h1>');
- Routing Example:
- Handle multiple paths:
o if (req.url === '/') {
o res.end('Home
Page');
o } else if (req.url === '/about') {
o res.end('About Page');
o } else {
o res.end('404 Not Found');
o }
Let me
know if you’d like additional examples or troubleshooting tips!
Comments
Post a Comment