Node.js | Automatically Generating an Express Web Application
Installing express-generator
Express applications can be generated from the command line with express-generator. Install it globally with npm.
$ npm install -g express-generator
After installation, create an application with the express command. The -e option selects EJS as the template engine.
$ express -e exapp
$ cd exapp
$ npm install
The generated application includes directories such as bin, public, routes, and views, plus files such as app.js and package.json. Start it with the generated server script.
$ node .\bin\www
The application runs on port 3000 by default, so it can be checked at http://localhost:3000/.
Structure of app.js
app.js is the center of the generated Express application. It loads libraries such as express, path, morgan, cookie-parser, and body-parser, then loads route scripts such as routes/index.
The important parts are:
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use("/", routes);
app.use("/users", users);
app.set configures application settings such as the view directory and template engine. app.use connects a URL path to a route module. The generated file also contains error handlers and finally exports the application with module.exports = app.
Routes and Templates
The generated routes/index.js uses express.Router. A route handler receives a request and response, then renders a template.
router.get("/", function(req, res, next) {
res.render("index", { title: "Express" });
});
The matching views/index.ejs template displays the values passed from the route.
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
This separation between route scripts and view templates is the basic Express structure.
Adding a New /helo Page
To add a new page, create routes/helo.js and views/helo.ejs, then register the route in app.js.
var helo = require("./routes/helo");
app.use("/helo", helo);
The route file can render the new template with its own data.
router.get("/", function(req, res, next) {
res.render("helo", {
title: "Hello",
message: "This is a new page."
});
});
By repeating this pattern, an Express application can be expanded page by page while keeping routing logic and templates organized.