First Node.js Program | Lecture 3

 

Here are notes on writing your first Node.js program:


First Node.js Program

Prerequisites:

  1. Install Node.js:
  2. Verify Installation:
    • Check the version of Node.js and npm:

o   node -v

o   npm -v


Steps to Create Your First Node.js Program:

  1. Setup a Project:
    • Create a new directory for your project.

o   mkdir first-node-app

o   cd first-node-app

  1. 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.
  1. 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   });

  1. 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:

  1. const http = require('http');:
    • Loads the HTTP module to create a web server.
  2. http.createServer():
    • Creates an HTTP server that listens for requests and sends responses.
  3. res.end('Hello, Node.js!');:
    • Sends the response text to the client.
  4. server.listen(PORT, callback):
    • Starts the server and listens on the specified port.

Enhancements:

  1. Using Console Logs:
    • Add logs to debug or confirm the server's actions.

o   console.log('Request received at', new Date());

  1. Serving HTML:
    • Modify the response to serve HTML:

o   res.setHeader('Content-Type', 'text/html');

o   res.end('<h1>Welcome to Node.js!</h1>');

  1. 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

Popular posts from this blog

Introduction to Node.js | Lecture 1

Introduction to NPM | Lecture 2

Modules in Node.js | Lecture 4