• No results found

What Is Express.js?

In document Practical Node js pdf (Page 39-42)

Express.js is a web framework based on the core Node.js http module and Connect (http://www.senchalabs.org/ connect/) components. The components are called middleware and they are the cornerstones of the framework philosophy configuration over convention. In other words, Express.js systems are highly configurable, which allows developers to pick freely whatever libraries they need for a particular project. For these reasons, the Express.js framework leads to flexibility and high customization in the development of web applications.

If you write serious apps using only core Node.js modules (refer to the following snippet for an example), you most likely find yourself reinventing the wheel by writing the same code continually for similar tasks, such as the following:

Parsing of HTTP request bodies

Parsing of cookies

Managing sessions

34

Organizing routes with a chain of

• if conditions based on URL paths and HTTP methods of

the requests

Determining proper response headers based on data types

To illustrate my point, here is an example of a two-route representational state transfer: http://en.wikipedia.org/wiki/Representational_state_transfer.

(REST) API server, i.e., we have only two end points and they are also called routes. In this application, we use only core Node.js modules for server functions. A single “userland”/external native MongoDB driver module is used for persistence. This example is taken from beginner-friendly Rapid Prototyping with JS (http://rpjs.co/): Agile JavaScript Development by Azat Mardan [2013]:

var http = require('http'); var util = require('util');

var querystring = require('querystring'); var mongo = require('mongodb');

var host = process.env.MONGOHQ_URL || 'mongodb://@127.0.0.1:27017';

//MONGOHQ_URL=mongodb://user:[email protected]/db_name mongo.Db.connect(host, function(error, client) {

if (error) throw error;

var collection = new mongo.Collection( client,

'test_collection' );

var app = http.createServer( function (request, response) { if (

request.method === 'GET' &&

request.url === '/messages/list.json' ) { collection.find().toArray(function(error, results) { response.writeHead( 200, {'Content-Type': 'text/plain'} ); console.dir(results); response.end(JSON.stringify(results)); }); }; if (

request.method === "POST" &&

request.url === "/messages/create.json" ) { request.on('data', function(data) { collection.insert( querystring.parse(data.toString('utf-8')), {safe: true}, function(error, obj) { if (error) throw error;

response.end(JSON.stringify(obj)); }

35

); }); }; });

var port = process.env.PORT || 5000; app.listen(port);

})

As you can see, developers have to do a lot of manual work themselves, such as interpreting HTTP methods and URLs into routes, and parsing input and output data.

Express.js solves these and many other problems as abstraction and code organization. The framework provides a model-view-controller-like (MVC-like) structure for your web apps with a clear separation of concerns (views, routes, models).

For the models (M in MVC), we need to use Mongoose (http://mongoosejs.com/) or Sequelize

(http://sequelizejs.com/) libraries in addition to Express.js— more on this later in the book in Chapter 7. In this chapter we’ll cover the basics of Express.js. Built on top this framework, Express.js applications can vary from bare-bones, back-end-only REST APIs to full-blown, highly scalable, full-stack with jade-browser (https://npmjs.org/package/ jade-browser) and Socket.IO (http://socket.io/), real-time web apps. To give some analogies to developers who are familiar with Ruby—Express.js is often seen as Sinatra, which has a very different approach to the Ruby on Rails framework. Express.js and Sinatra promote the configurability while Ruby on Rails convention over configuration.

Although Express.js is the most starred library on NPM (as of May 2014), and the most mature and used Node. js framework, the playing field is still relatively level with many different frameworks, and new ones are released every month. Some of them, such as Meteor (http://meteor.com/) and DerbyJS (http://derbyjs.com/), show an interesting trend in attempts to merge front-end and back-end code bases. For a handpicked list of Node.js frameworks, refer to the Node Framework (http://nodeframework.com/) resource.

When evaluating a Node.js framework for your project, use these easy steps to guide you: Build a sample app which is usually provided by the creators of frameworks on GitHub or

official web sites. See how the app feels in terms of styles and patterns.

Consider the type of application you’re building: prototype, production app, minimum viable

product (MVP), small scale, large scale, and so on.

Consider the libraries already familiar to you and determine whether you can or plan to reuse

them, and whether your framework plays nicely with them. Provide out-of-the-box solutions: template engines, database object-relational mapping (http://en.wikipedia.org/wiki/ Object-relational_mapping) libraries (ORMs) / drivers, cascading style sheets

(http://en.wikipedia.org/wiki/Cascading_Style_Sheets) (CSS) frameworks. Consider the nature of your application: REST API (with a separate front-end client), a

traditional web app, or a traditional web app with REST API end points (such as Blog). Consider whether you need the support of reactive templates with WebSocket from the

get-go. (the Meteor framework, anyone?)

Evaluate the number of stars and follows on NPM and GitHub to judge the popularity of the

framework. More popular typically means more blog posts, books, screencasts, tutorials, and programmers exist; less popular means this is a newer framework, a niche/custom choice, or a poor choice. With newer frameworks, there is a greater chance that contributing back to them will be valued, so pick your comfortable spot.

Evaluate NPM, GitHub pages, and a framework’s website for the presence of good API

documentation with examples or open issues/bugs. If there are more than a few hundred, depending on popularity, this may not be a good sign. Also, determine the date of the last commit on the GitHub repository. Anything older than six months is not a good sign.

36

In document Practical Node js pdf (Page 39-42)