• No results found

The App.js File

In document Practical Node js pdf (Page 57-61)

The app.js file is the main file for this example. A typical structure of the main Express.js file consists of the following areas (this may be a partial repeat from an earlier section, but this is important, so bear with me):

1. Require dependencies 2. Configure settings

3. Connect to database (optional) 4. Define middleware

5. Define routes 6. Start the server

7. Start workers with clusters (a term spawn workers is also used for this) (optional)

The order here is important, because requests travel from top to bottom in the chain of middleware.

Let’s perform a quintessential programming exercise: writing the Hello World application. This app transitions smoothly into the Blog example project, so no effort is wasted!

Open app.js in a code editor of your choice and start writing or just copy the code from GitHub at http://github.com/azat-co/blog-express.

First, all the dependencies need to be included with require():

var express = require('express'); var http = require('http'); var path = require('path');

Then, the Express.js object is instantiated (Express.js uses a functional pattern):

52

One of the ways to configure Express.js settings is to use app.set(), with the name of the setting and the value. For example:

app.set('appName', hello-world');

Let’s define a few such configurations in app.js:

• port: a number on which our server should listen to requests

• views: absolute path to the folder with template (views in our example)

• view engine: file extension for the template files (for example, jade, html)

If we want to use the port number provided in the environmental variables (env vars), this is how to access it:

process.evn.PORT.

So let’s write the code for the settings we listed earlier:

app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade');

Next comes the middleware section of the application. Middleware is the backbone of the Express.js framework and it comes in two flavors:

1. Defined in external (third-party) modules, such as bodyParser.json from Connect/ Express.js body-parser: app.use(bodyParser.json());

2. Defined in the app or its modules, such as app.use(function(req, res, next){...});

Middleware is a way to organize and reuse code, and, essentially, it is nothing more than a function with three parameters: request, response, and next. We’ll use more middleware (for example, for authorization and for persistence) in Chapter 6, but for now, its use is minimal.

The next components in the app.js file are routes. Routes are processed in the order they are defined. Usually, routes are put after middleware, but some middleware may be placed following the routes. A good example of such middleware, found after a routes, is error handler.

53

The next section is where we define routes themselves (the order in app.js matters). The way routes are defined in Express.js is with helpers app.VERB(url, fn1, fn2, ..., fn), where fnNs are request handlers, url is on a URL pattern in RegExp, and VERB values are as follows:

• all: catch every request (all methods)

• get: catch GET requests

• post: catch POST requests

• put: catch PUT requests

• del: catch DELETE requests

Note

del

and

delete

methods are aliases, just remember that

delete

is a valid operator in javascript/eCMascript,

and therefore in node.js. the operator removes a property from an object, e.g.,

delete books.nodeInAction

.

Figure 2-11 shows how a trivial request might travel across the web and the Express.js app, with the dotted lines being the connection inside it.

Following a simple request in an Express.js app. Browser Give me a resource Give me data Give me a template The template The data Compile data and template

into HTML or JSON/XML/etx Send HTML or JSON/XML/etc back Look up URL in routes Rule is found Find data

Find the template

App dp View

Browser App dp View

54

In this Hello World example a single route is used to catch requests of all methods on all URLs (* wildcard):

app.all('*', function(req, res) { ...

})

Inside the request handler, a template is rendered (res.render() function) with a message msg (property of the second argument):

app.all('*', function(req, res) {

res.render('index', {msg: 'Welcome to the Practical Node.js!'}) })

The res.render(viewName, data, callback(error, html)) where parameters mean following:

• viewName: a template name with filename extension or if view engine is set without the extension

• data: an optional object that is passed as locals; for example, to use msg in Jade, we need to have {msg: "..."}

• callback: an optional function that is called with an error and HTML when the compilation is complete

res.render() is not in the Node.js core and is purely an Express.js addition that, if invoked, calls core res.end(), which ends/completes the response. In other words, the middleware chain doesn’t proceed after res.render(). res.render is highlighted in chapter 4.

Last but not least are the instructions to start the server, which consist of the core http module and its

createServer method. In this method, the system passes the Express.js app object with all the settings and routes:

http.createServer(app).listen(app.get('port'), function(){

console.log('Express server listening on port ' + app.get('port')); });

Here’s the full source code of the app.js file for your reference:

var express = require('express'); var http = require('http'); var path = require('path'); var app = express();

app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade');

app.all('*', function(req, res) { res.render(

'index',

{msg: 'Welcome to the Practical Node.js!'} );

55

http .createServer(app) .listen( app.get('port'), function(){ console.log(

'Express.js server listening on port ' + app.get('port')

); } );

Before we can run this server, we need to create the index.jade file.

In document Practical Node js pdf (Page 57-61)