How to bootstrap a Node.js HTTP service project

A small HTTP service project gives a Node.js directory the files needed to start, answer a request, and grow into a larger application. Bootstrapping the project with npm and the built-in node:http module keeps the first endpoint dependency-free while still using the same package.json script flow used by larger services.

The project uses server.js with CommonJS require() so it runs in a default npm package without adding a module-type decision first. The service binds to 127.0.0.1 for local development and reads PORT from the environment before falling back to port 3000.

The finished directory contains package.json plus server.js. npm start launches the listener, and a curl request to the root path confirms that the service returns the expected response before additional routes, dependencies, or deployment files are added.

Steps to bootstrap a Node.js HTTP service project:

  1. Create the project directory.
    $ mkdir inventory-service
  2. Enter the project directory.
    $ cd inventory-service
  3. Initialize package metadata with npm.
    $ npm init --yes

    The --yes flag writes default package.json values from the directory name and skips the questionnaire.

  4. Add a start script that runs the server file.
    $ npm pkg set scripts.start="node server.js"

    npm pkg set edits package.json directly and preserves valid JSON formatting.

  5. Create the HTTP service file.
    $ cat > server.js <<'EOF'
    const http = require('node:http');
    
    const hostname = '127.0.0.1';
    const port = process.env.PORT || 3000;
    
    const server = http.createServer((req, res) => {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('Inventory service is running\n');
    });
    
    server.listen(port, hostname, () => {
      console.log(`Server running at http://${hostname}:${port}/`);
    });
    EOF

    Binding to 127.0.0.1 keeps the starter service local while the project is still being built.

  6. Check the saved start script.
    $ npm pkg get scripts.start
    "node server.js"
  7. Start the service with npm.
    $ npm start
    
    > inventory-service@1.0.0 start
    > node server.js
    
    Server running at http://127.0.0.1:3000/

    Keep this terminal open while testing the listener from another terminal.

  8. Request the root path from another terminal.
    $ curl -sS http://127.0.0.1:3000/
    Inventory service is running
  9. Return to the npm start terminal and press Ctrl-C.