Express.js is a popular Node.js web framework. Because of its support for routing and view engines it makes it easy to create web applications using Express.js. One other tool that can make life easy is the express-generator which is an express application generation tool that can quickly create an application skeleton.
Using express-generator
Using express-generator you can quickly create a standard project structure for you ExpressJS application by using a single command.
express-generator Installation
You can install express-generator globally using the following command. Ensure you already have Node.js and Express.js installed in your system.
npm install -g express-generatoror by using
npx express-generator
Once express-generator is installed you can create an Express.js app by using the command as given below.
express EXPRESSJSAPP_NAME
For example, running the command
>express myexpressapp
creates an Express app named myexpressapp. The app will be created in a folder named myexpressapp in the current working directory. Note that by default the selected view engine is Jade and the stylesheet engine support defaults to plain CSS.
You can change the above-mentioned defaults by using the following options-
- -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
- -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
For example, if you want to use ejs as view engine then you can use the following command to generate a project structure accordingly.
>express --view=ejs myexpressapp create : myexpressapp\ create : myexpressapp\public\ create : myexpressapp\public\javascripts\ create : myexpressapp\public\images\ create : myexpressapp\public\stylesheets\ create : myexpressapp\public\stylesheets\style.css create : myexpressapp\routes\ create : myexpressapp\routes\index.js create : myexpressapp\routes\users.js create : myexpressapp\views\ create : myexpressapp\views\error.ejs create : myexpressapp\views\index.ejs create : myexpressapp\app.js create : myexpressapp\package.json create : myexpressapp\bin\ create : myexpressapp\bin\www change directory: > cd myexpressapp install dependencies: > npm install run the app: > SET DEBUG=myexpressapp:* & npm start
As given in the instructions change location to the generated project directory
D:\knpcode>cd myexpressapp
and run the command
D:\knpcode\myexpressapp>npm install
This will install all the project dependencies (Refer the generated package.json for the project dependencies).
Following image shows the generated project structure.
Running the application
Generated app has some basic routing and views already existing so you can run the app and see a view.
Run the following command to start the server
D:\knpcode\myexpressapp>npm start
Default port number is 3000 so you can access the application by using http://localhost:3000 that gives the following view.
Let's go through the project flow to understand how we reach this view.
Mapping to the root ('/') is in routes/index.js file.
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); module.exports = router;
As you can see get mapping for root renders the index.ejs file by using the res.render() method in its callback.
This index.ejs file is located in views folder.
<!DOCTYPE html> <html> <head> <title><%= title %></title> <link rel='stylesheet' href='/stylesheets/style.css' /> </head> <body> <h1><%= title %></h1> <p>Welcome to <%= title %></p> </body> </html>
app.js is the main file which sets the view engine as ejs and sets the routes defined in routes folder.
var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', indexRouter); app.use('/users', usersRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app;
View engine setup is done in these lines
// view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs');
Route setup is done in these lines-
var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); app.use('/', indexRouter); app.use('/users', usersRouter);
That's all for the topic Using express-generator to Create ExpressJS App Structure. If something is missing or you have something to share about the topic please write a comment.
You may also like
- Express body-parser With Examples
- ExpressJS Redirect Using res.redirect()
- Express File Download Using res.download()
- ExpressJS: Pug Template Engine Integration With Examples
- ExpressJS Middleware Functions
- First React App – Hello World React Example
- HTTP GET Method in React - fetch, Axios
- Spring Boot Hello World Application
- Convert HTML to PDF in Java Using Flying Saucer, OpenPDF
- ConcurrentLinkedDeque in Java With Examples
No comments:
Post a Comment