Skip to content

Instantly share code, notes, and snippets.

@gregfenton
Last active March 10, 2023 17:43
Show Gist options
  • Save gregfenton/6660d8541ecf6de84a1e2bf75809326f to your computer and use it in GitHub Desktop.
Save gregfenton/6660d8541ecf6de84a1e2bf75809326f to your computer and use it in GitHub Desktop.
Express: Start and write to console

ExpressJS: Start, Listen and Console.log()

Prerequisites

  1. Initialized npm project with package.json file. See: Getting started with npm.
  2. express installed as project dependency.
  3. Entry page (i.e. server.js) present in the project root.

Example directory structure

project-root
    ├── node_modules
    ├── package-lock.json
    ├── package.json
    └── server.js

Instructions

  1. In your favourite editor (VSCode), open the file server.js

  2. Add JS code to load express as a program dependency:

    const express = require('express');
  3. Create an instance of the Express server. Express wants you to start by invoking the function that express exports to require().

    const app = express();
    • express() returns a JS object. It includes many functions that come in handy. Let's use those functions now.
  4. Set a variable for the port that the server will listed to. For now, let's go with port 4000:

    const PORT = 4000;
  5. Instruct the server to listen to the PORT:

    app.listen(PORT, function(){
      console.log(`Listening on port ${PORT}`);
    });
  • Our node program (an Express server!) will start in the terminal window (making it pretty useless, besides logging to the console).
{
"name": "hello-express",
"version": "1.0.0",
"description": "An introductory express app",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "InceptionU",
"license": "MIT",
"dependencies": {
"express": "^4.17.1"
}
}
const express = require('express');
const app = express();
const PORT = process.env.PORT || 4000;
//
// Start up and wait for incoming requests
//
app.listen(PORT, function() {
console.log(`Listening on port ${PORT}`);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment