Skip to content

Start the Express Engine

To get this machine on the road, we need to do three things:

  1. Require the package.
  2. Initialize the app (turn the key).
  3. Listen on a port (step on the gas).
'use strict';
/**
* Node2Know — Basic Express Server
*
* Express is an opinionated layer on top of Node’s http server:
* - you get an app object
* - you attach routes + middleware
* - you start listening on a port
*/
const express = require('express');
// The ignition: this creates the Express application instance.
// Think of `app` as your server control panel (routes, middleware, config).
const app = express();
// Define the port:
// - Use the environment variable if the host provides one (common in deployment)
// - Otherwise default to 3000 locally
const PORT = process.env.PORT || 3000;
// Hit the gas: start the server.
// The callback runs once, when the server is successfully listening.
app.listen(PORT, () => {
console.log(`Created process at PID: ${process.pid}`);
console.log(`Listening on port: ${PORT}`);
console.log(`Try: http://localhost:${PORT}`);
});

Solo Warning: Note that app.listen is asynchronous. The callback function runs after the server successfully binds to the port. Don’t try to drive before the engine starts.


Environment Variables: The Road Conditions

Section titled “Environment Variables: The Road Conditions”

You see that process.env.PORT line? That’s us checking the road conditions.

When we deploy this server to a cloud host (the autobahn), they tell us which lane (port) to drive in. We don’t get to pick. If process.env.PORT is defined by the environment, we use it. If not (like when we’re testing in the garage), we fall back to 3000.

process.env is the global dashboard for your Node process. It holds all the critical stats: API keys, database URLs, and port numbers.

You can check your current environment variables in the REPL:

Terminal window
$ node
> console.log(process.env)

If you see a wall of text, congratulations, your dashboard is working.


Basic Express Server - Demo Repo

Node.js Env Vars Guide

⏭ Basic Directions

Engine’s running. Now we need to tell the traffic where to go.