Skip to content

express

Fast, unopinionated, minimalist web framework for node.

This would be a minimal express application.

const express = require('express')
const app = express()

app.get('/', function (req, res) {
  res.send('Hello World')
})

app.listen(3000)

But you need some more infrastructure to run it.

mkdir test
cd test
npm install -g express-generator@4
express --hbs myapp
cd myapp
npm install
npm start

Then browse to http://localhost:3000.

It will show

Express
Welcome to Express

The app.js file contains a lot of boilerplate code that was generated. Is it needed to know what it does ? The --hbs option is needed to get 'handlebars' (hbs) templates which i like better because of the {{moustache}} format.

The directory layout is :

.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.hbs
    ├── index.hbs
    └── layout.hbs

Note that app.js is the main source file for this express app, and bin/www is the server startup binary. This will run the app at port :3000

bin/www

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('tasks:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

It is a node executable as the first line shows, it includes the app.js source file and note that it is not minified It can be minified into a bundle, but as-is this is just a standalone app.

What we did with browserify was this build line

browserify src/main.js -p esmify -o public/bundle.js --debug

This combines main.js into the bundle and it now has to be started differently from express.