All notes
Express

Intro

github: migrate from 3.x to 4.x.

A very good example blog: aleksandrov.ws.

Port

SO: js express on port.


process.env.PORT

Simple example



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

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(3000, () => console.log('Example app listening on port 3000!'))

Commandlines

express


npm install express-generator -g

# the view engine will be set to Pug:
express --view=pug myapp

cd myapp
npm install
# On MacOS or Linux, run the app with this command:
DEBUG=myapp:* npm start
# On Windows, use this command:
set DEBUG=myapp:* & npm start

Topics

Serving static files

expressjs.com: static files.



express.static(root, [options])
// The root argument specifies the root directory from which to serve static assets.

app.use(express.static('public'))
// If "public" directory has: images/, css/, js/, images/, hello.html.
// http://localhost:3000/images/kitten.jpg
// http://localhost:3000/css/style.css
// http://localhost:3000/js/app.js
// http://localhost:3000/images/bg.png
// http://localhost:3000/hello.html

app.use('/static', express.static('public'))
// Now, you can load the files that are in the public directory from the /static path prefix.
// http://localhost:3000/static/images/kitten.jpg
// http://localhost:3000/static/css/style.css
// http://localhost:3000/static/js/app.js
// http://localhost:3000/static/images/bg.png
// http://localhost:3000/static/hello.html

// To use the absolute path of the directory that you want to serve:
app.use('/static', express.static(path.join(__dirname, 'public')))

// To use multiple static assets directories, call the express.static middleware function multiple times:
app.use(express.static('public'))
app.use(express.static('files'))