Using Express Generator
1. Installing express-generator
| Command | Purpose |
|---|---|
npm install -g express-generator | Global install |
npx express-generator | One-off without install RECOMMENDED |
express --help | List options |
2. Creating New Projects
Example: Scaffold project
npx express-generator my-app --view=ejs --git
cd my-app
npm install
npm start # runs DEBUG=my-app:* node ./bin/www
| Flag | Effect |
|---|---|
--view <engine> | ejs, pug, hbs, hjs, jade, twig, vash |
--no-view | Skip view engine (API-only) |
--css <preprocessor> | less, stylus, compass, sass |
--git | Add .gitignore |
-f, --force | Force on non-empty directory |
3. Specifying View Engine
| Engine | Syntax Style |
|---|---|
| EJS | HTML with <% %> tags |
| Pug | Indentation-based, terse |
| Handlebars (hbs) | Logic-less {{var}} |
| Twig | Symfony-style |
4. Generating with CSS Preprocessors
| Preprocessor | Generated middleware |
|---|---|
| sass | node-sass-middleware |
| less | less-middleware |
| stylus | stylus middleware |
5. Adding Git Ignore Files
| Flag | Result |
|---|---|
--git | Adds standard .gitignore |
6. Understanding Generated Structure
my-app/
├── bin/
│ └── www ← server bootstrap (port + listen)
├── public/ ← static assets
│ ├── images/
│ ├── javascripts/
│ └── stylesheets/
├── routes/
│ ├── index.js
│ └── users.js
├── views/
│ ├── error.ejs
│ ├── index.ejs
│ └── layout.ejs
├── app.js ← Express app definition
└── package.json
| File | Role |
|---|---|
bin/www | Creates HTTP server, normalizes port, binds app.listen() |
app.js | Application + middleware + route mounting |
routes/ | One express.Router() per resource |
7. Installing Dependencies
| Command | Purpose |
|---|---|
npm ci | Clean reproducible install (CI/CD) |
npm install --omit=dev | Production install (no devDeps) |
8. Starting Generated Application
| Command | Behavior |
|---|---|
npm start | node ./bin/www |
DEBUG=my-app:* npm start | Verbose debug output |
npx nodemon ./bin/www | Auto-restart on changes |
node --watch ./bin/www | Native watch mode NODE 18.11+ |
9. Customizing Generated Templates
| Customization | Where |
|---|---|
| Add middleware | app.js (between body parsers and routes) |
| Add routes | New file in routes/, mount in app.js |
| Change layout | views/layout.ejs |
| Replace view engine | Update app.set("view engine") + reinstall |
10. Using npx for One-Time Execution
Example: Quick prototype
npx express-generator --no-view --git --force ./
npm install
node ./bin/www
| Benefit | Detail |
|---|---|
| Always latest | Pulls from npm cache |
| No global pollution | Nothing installed permanently |
| Version pinning | npx express-generator@4.16.1 |
Note: express-generator targets Express 4. For Express 5+ projects, hand-craft the structure or use a modern starter (e.g. Fastify, Hono) for native ESM + TypeScript.