As we know Express is the most commonly used web framework in node.It has many features such as rendering, routing and REST controls.
But in this post we are going to discuss about express-generator. Express-generator is a application generator tools, which creates a skeleton of your application quickly.
Express-Generator is different from Express as it creates a skeleton for express-driven sites.
Here we will create a sample application using express-generator that will print Hello World.
For that first we need to install express generator with the below command. Here i am assuming that node is already installed on your system.
$ npm install express-generator -g
Now express-generator is installed as a global command on our system. Now we will create an Express app named mynodeapp in the current working directory:
$ express mynodeapp
It will create a file structure like this:
app.js
bin
www
package.json
public
images
javascripts
stylesheets
style.css
routes
index.js
users.js
views
error.jade
index.jade
layout.jade
Now next step is to install dependency. Express-generator created a file called package.json in your mynodeapp directory. Open this file in a text editor and
do some changes if required for example calls for MongoDB but in our case, we have not done any changes to this file.Now install dependencies.
$ cd mynodeapp
$ npm install
Here Express scaffolding already defined the "routes" variable in the file \mynodeapp\routes\index.js). In your text editor, open this index.js file. It will look like this:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Replace the above code with this code:
var express = require('express');
var router = express.Router();
var app = express();
/* GET Hello World page. */
router.get('/helloworld', function(req, res) {
res.render('helloworld', { title: 'Hello, World!' });
});
module.exports = router;
Here we have added a helloworld method to this router which will render a different page instead of this default page.
But we don't have any page helloworld to render. So we will create a new file, and save it as helloworld.jade.
Open this file and put the below code:
extends layout
block content
h1= title
p Welcome to #{title}
p Hello, World! Welcome to #{title}
Now go to the command prompt and then type:
npm start
After starting the server open browser and navigate to http://localhost:3000/helloworld
You will see the message "Hello World".
0 Comment(s)