Over a million developers have joined DZone.

Node.js: Using Connect with Express

· Performance Zone

See Gartner’s latest research on the application performance monitoring landscape and how APM suites are becoming more and more critical to the business, brought to you in partnership with AppDynamics.

Connect is a middleware framework for Nodejs and is used in several projects like Express. Today I’ll show you a simple example of how to use some of the Connect bundled middleware in an Express application.

Assuming you have Nodejs installed and are ready to go, make sure to use npm to install the latest Express. I’ll install mine locally to the folder I’m currently working in like this:

$ npm install express

Lets use the Connect logger and responseTime middleware. The logger gives a configurable output and the responseTime will tell you how long a response took by placing a value in the headers (X-Response-Time).

Create a new file called app.js and add the following code:

var express = require('express');
var app = express.createServer(
app.get('/', function(request, response) {
    response.send('Hello World');
console.log('Starting server...')

You can see how easy it is to add Connect middleware. Using Express you simply add the middleware you want, in this case I added it in via createServer.

Now go to the URL (you might want to use a browser add-on to see the headers more easily, for Chrome try the XHR Poster). In the header you should see something similar to this:

X-Response-Time 0ms

Obviously our server is so fast at this point since it only serves up the text “Hello World” that it took essentially no time to process and response. However if you were actually doing some something more you will see the value go up. Just as an example you could temporarily block the server with a timer if you wanted to see the value change.

In the output you will see the logging: - - [Sun, 15 Jan 2012 23:57:13 GMT]
"GET / HTTP/1.1" 200 11 "-"
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2)
AppleWebKit/535.7 (KHTML, like Gecko)
Chrome/16.0.912.75 Safari/535.7"


From http://www.giantflyingsaucer.com/blog/?p=3537

The Performance Zone is brought to you in partnership with AppDynamics.  See Gartner’s latest research on the application performance monitoring landscape and how APM suites are becoming more and more critical to the business.


Published at DZone with permission of Chad Lung, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}