Start the Express Engine
Turning the Key
Section titled “Turning the Key”To get this machine on the road, we need to do three things:
- Require the package.
- Initialize the app (turn the key).
- Listen on a port (step on the gas).
app.js
Section titled “app.js”'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 locallyconst 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.listenis 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.
Checking the Dashboard
Section titled “Checking the Dashboard”You can check your current environment variables in the REPL:
$ node> console.log(process.env)If you see a wall of text, congratulations, your dashboard is working.
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Basic Express Server - Demo Repo
Node.js Env Vars Guide