Prerequisites
Before starting, We need to have a local development environment for Node.js. If haven’t installed Node.js yet, first Install Nodejs in website Instal Nodejs .
Step 1: Create a New Project Folder
First, create a new folder for the project by running the following command in your terminal:
mkdir myapp && cd myappStep 2: Initialize a New Node.js Project
Next, initialize a new Node.js project by running the following command:
npm init -yStep 3: Install Express.js
Now, install Express.js by running the following command:
npm install expressStep 4: Create an Express.js Application
Create a new file named app.js in our project folder and open it in your text editor. In this file, write the following code:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});Step 5: Run the Express.js Application
Finally, run Express.js application by running the following command:
node app.js We can now open Our web browser and navigate to http://localhost:3000 to see “Hello World!”
Create Project with Express application generator
Install Generator Global
sudo npm install -g express-generator@latestDisplay the command options with the -h option:
express -h Options:
-h, --help output usage information
--version output the version number
-e, --ejs add ejs engine support
--hbs add handlebars engine support
--pug add pug engine support
-H, --hogan add hogan.js engine support
--no-view generate without view engine
-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)
--git add .gitignore
-f, --force force on non-empty directory
Then Create Project, Fro example use ejs as a template engine:
express --view=ejs myapp
Go to project directory and install depedencies:
cd myappInstall Depedencies:
npm installRun Project
DEBUG=myapp:* npm startNow we can open browser and access routes like : http://localhost:3000 OR http://localhost:3000/users
The generate structure with see like this:
.
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.ejs
├── index.ejs
Happy Coding!