How can you develop a simple website using node.js as the backend and HTML/CSS as the front-end?

Developing a simple website using Node.js for the backend and HTML/CSS for the front-end involves several steps. Below is a basic guide to get you started:

Step 1: Set Up Your Project

  1. Install Node.js:

  2. Create a Project Folder:

    • Create a new folder for your project.
  3. Initialize a Node.js Project:

    • Open a terminal in your project folder and run:

        bashCopy codenpm init -y
      

Step 2: Create Backend with Node.js

  1. Install Express:

    • Express is a popular web framework for Node.js. Install it using:

        bashCopy codenpm install express
      
  2. Create app.js (or index.js):

    • Create a file (e.g., app.js) for your Node.js server.

    • Set up a basic Express server:

        javascriptCopy codeconst express = require('express');
        const app = express();
        const port = 3000;
      
        app.get('/', (req, res) => {
          res.send('Hello World!');
        });
      
        app.listen(port, () => {
          console.log(`Server listening at http://localhost:${port}`);
        });
      
  3. Run Your Server:

    • Execute your Node.js server:

        bashCopy codenode app.js
      

Step 3: Create Frontend with HTML/CSS

  1. Create public Folder:

    • Create a public folder in your project directory to store static files.
  2. Create HTML and CSS Files:

    • Inside the public folder, create an index.html file and a style.css file.

    • Add some basic content to index.html and style it in style.css.

Example index.html:

    htmlCopy code<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href="/style.css">
      <title>Node.js Website</title>
    </head>
    <body>
      <h1>Hello from Node.js!</h1>
    </body>
    </html>

Example style.css:

    cssCopy codebody {
      font-family: Arial, sans-serif;
      background-color: #f0f0f0;
      text-align: center;
      padding: 20px;
    }

    h1 {
      color: #333;
    }

Step 4: Serve Static Files with Express

  1. Update app.js:

    • Modify your app.js file to serve static files from the public folder.
    javascriptCopy codeconst express = require('express');
    const app = express();
    const port = 3000;

    app.use(express.static('public'));

    app.get('/', (req, res) => {
      res.sendFile(__dirname + '/public/index.html');
    });

    app.listen(port, () => {
      console.log(`Server listening at http://localhost:${port}`);
    });
  1. Restart Your Server:

    • Stop your running Node.js server (press Ctrl+C) and restart it:

        bashCopy codenode app.js