Skip to content
The Chat Archive
gpt-4o-2024-05-13· OpenAI WildChat-4.8M (AI2)

node.js example

  1. User

    node.js example

  2. Assistant

    Certainly! Below you'll find an example of a simple Node.js application that sets up a basic web server using the built-in http module.

    1. Initialization: First, ensure you have Node.js installed. You can download it from nodejs.org.

    2. Create the server:

    Here's a basic example showing how to create a server:

    // Load the http module to create an HTTP server.
    const http = require('http');
    
    // Configure the HTTP server to respond with "Hello, World!" to all requests.
    const server = http.createServer((req, res) => {
        // Set the HTTP response header with HTTP status and Content type
        res.writeHead(200, {'Content-Type': 'text/plain'});
        // Send the response body as "Hello, World!"
        res.end('Hello, World!\n');
    });
    
    // Listen on port 3000, IP defaults to 127.0.0.1
    server.listen(3000, '127.0.0.1', () => {
        console.log('Node.js server is running at http://127.0.0.1:3000/');
    });
    
    1. Run the server:

    Save the code to a file named server.js and run it using Node.js:

    node server.js
    
    1. Access the server:

    Open a web browser and navigate to http://127.0.0.1:3000/. You should see "Hello, World!" displayed on the page.


    Advanced Example with Express.js

    For more advanced web applications, developers often use frameworks like Express.js. Here's how to set up a basic server using Express:

    Install Express

    First, create a new directory for your project and initialize a new Node.js project:

    mkdir myapp
    cd myapp
    npm init -y
    

    Then, install Express:

    npm install express
    

    Create a server with Express

    Create a file named app.js and add the following code:

    const express = require('express');
    const app = express();
    const port = 3000;
    
    // Define a route for the root path
    app.get('/', (req, res) => {
        res.send('Hello, World!');
    });
    
    // Start the server and listen on port 3000
    app.listen(port, () => {
        console.log(`Example app listening at http://localhost:${port}`);
    });
    

    Run the server

    Start your server by running:

    node app.js
    

    Access the server

    Open a web browser and navigate to http://localhost:3000/. You should see "Hello, World!" displayed on the page.

    This Express example provides a more scalable and flexible way to build web applications compared to using the built-in http module.