Skip to content
This repository
Browse code

Update the connect-it article for latest node and connect APIs

  • Loading branch information...
commit 5d335f9e2fa6d7d4b61e7c967c8cdbeaa884b839 1 parent f7775fd
Tim Caswell authored
29  articles/connect-it.markdown
Source Rendered
... ...
@@ -1,12 +1,14 @@
1 1
 Title: Just Connect it Already
2 2
 Author: Tim Caswell
3 3
 Date: Mon Jun 07 2010 12:22:52 GMT-0700 (PDT)
4  
-Node: v0.1.97
  4
+Node: v0.1.102
5 5
 
6 6
 Now that the core APIs of node are really starting to stabilize, I'm moving my attention to helping stabilize the framework scene.  One of the things I found really neat from Ruby was the [Rack][] server interface.  It allowed any server that followed the spec to host any app that followed the spec.  Also (and this is the important part for node) is allowed for generic middleware libraries to do common tasks and functions in a very aspect oriented manner.
7 7
 
8 8
 My employer, [Sencha][], has sponsored [TJ Holowaychuk][] and I to write a middleware system for node called [Connect][] in an effort to foster common development in the node community.
9 9
 
  10
+**UPDATE** This article has been updated to use the new connect middleware API.
  11
+
10 12
 ## So What's New?
11 13
 
12 14
 Actually there isn't a lot new here.  But then again, there was nothing new about node either.  Node uses non-blocking IO for fast scalable servers.  That's been known about for years among the C community.  It uses event based, single thread javascript for logic.  That's exactly what the browser has. Add these together and we all see the huge splash it's made.  It's the unique combination of some simple but complimentary ideas that really make these projects zing.
@@ -60,9 +62,9 @@ Let's go through a simple app from the top down.  It will serve JavaScript files
60 62
 
61 63
 <connect-it/app.js>
62 64
 
63  
-An app is just a call to `Connect.createServer` with an array of middleware config lines.
  65
+An app is just a call to `Connect.createServer` with several handlers in a row.
64 66
 
65  
-All Connect middlewares are simply node modules that export a `handle` function.  This function will be called by the connect engine when it gets to that layer of the application.  You have the option at this point to either: A) Serve a response using the `res` parameter. or B) Pass on control to the next layer in the chain using the `next` parameter.  Since you have raw access to the node request and response objects and the full JavaScript language, the possibilities are endless.
  67
+All Connect layers are simply node modules that export a `setup` function that returns a `handle` function.  The setup function is called at server startup and you can pass in configuration parameters to it.  Then on each request, you have the option at this point to either: A) Serve a response using the `res` parameter. or B) Pass on control to the next layer in the chain using the `next` parameter.  Since you have raw access to the node request and response objects and the full JavaScript language, the possibilities are endless.
66 68
 
67 69
 ### Serve Some Files
68 70
 
@@ -78,11 +80,11 @@ Whenever there is a problem with a server, it's really great to have a log-file
78 80
 
79 81
 <connect-it/log-it.js>
80 82
 
81  
-Connect modules also support a `setup` function that gets called once on server startup.  This is a great place to setup variables used by the middleware.  In this case we're initializing the counter for the logger.
  83
+The setup function is a great place to setup variables used by the middleware across requests.  In this case we're initializing the counter for the logger.
82 84
 
83  
-In `handle` we are using a wrapping idiom to hook into the call to `writeHead`.  In JavaScript functions are values just like anything else.  So a great way to wrap functions is to store a reference to the original implementation in a closure variable.  Replace the function with a new one, and in the first line of the new function, put the old function definition back.  Then on the last line of the replacement function call the original.  This is a simple and efficient way to hook into existing object methods since they just look for properties by name and not references to actual function objects.
  85
+In the handler we are using a wrapping idiom to hook into the call to `writeHead`.  In JavaScript functions are values just like anything else.  So a great way to wrap functions is to store a reference to the original implementation in a closure variable.  Replace the function with a new one, and in the first line of the new function, put the old function definition back.  Then on the last line of the replacement function call the original.  This is a simple and efficient way to hook into existing object methods since they just look for properties by name and not references to actual function objects.
84 86
 
85  
-The standalone `puts` call will be called at the beginning of each request cycle, and the nested `puts` will be called on the way out by means of the nested `writeHead` function.
  87
+The standalone `console.log` call will be called at the beginning of each request cycle, and the nested `console.log` will be called on the way out by means of the nested `writeHead` function.
86 88
 
87 89
 ## Built-in Middleware
88 90
 
@@ -90,7 +92,7 @@ Connect comes with several built-in middleware layers for easy use.  A much more
90 92
 
91 93
 <connect-it/app2.js>
92 94
 
93  
-This has proper error-handline, proper HTTP headers, and all sorts of other bells and whistles that are required from a production web server.
  95
+This has proper error-handling, proper HTTP headers, and all sorts of other bells and whistles that are required from a production web server.
94 96
 
95 97
 ## Future and Goals of Connect
96 98
 
@@ -106,14 +108,20 @@ There has been a lot of discussion on the topic of middleware and now is the tim
106 108
 
107 109
 Connect is cool, I gave two presentations on it in the past week at [txjs][] and [swdc][] and people loved it. TJ and I have done all we can for now and need some community feedback in order to move on.  If you are interested in node and want to help shape the future of web frameworks please do the following:
108 110
 
109  
- - Install node if you haven't already. (I suggest using [nvm][])
  111
+ - Install node if you haven't already. (I suggest using [ivy][])
110 112
  - Clone Connect.
111 113
  - Go through the examples in the code-base. (The `app.js` file is launched with the `connect` executable)
112 114
  - Write your own code using Connect. (Or port your favorite node framework)
113 115
  - Send feedback through [github][] and the normal node community channels. (irc and mailing list)
114 116
  - Tweet about it to spread the word. (This only works if everyone uses it)
115 117
 
  118
+### Deploying Connect Apps
  119
+
  120
+See the [deploying-node-with-spark][] article for tips on how to set up a production server using [Connect][] and [Spark][].
  121
+
  122
+
116 123
 [Connect]: http://github.com/senchalabs/connect
  124
+[Spark]: http://github.com/senchalabs/spark
117 125
 [Sencha]: http://sencha.com/
118 126
 [TJ Holowaychuk]: http://github.com/visionmedia
119 127
 [ejsgi]: http://github.com/isaacs/ejsgi
@@ -121,5 +129,6 @@ Connect is cool, I gave two presentations on it in the past week at [txjs][] and
121 129
 [wheat]: http://github.com/creationix/wheat
122 130
 [txjs]: http://www.slideshare.net/creationix/real-time-web-with-node
123 131
 [swdc]: http://www.slideshare.net/creationix/node-powered-mobile
124  
-[nvm]: http://github.com/creationix/nvm
125  
-[github]: http://github.com/senchalabs/connect/issues
  132
+[ivy]: http://github.com/creationix/ivy
  133
+[github]: http://github.com/senchalabs/connect/issues
  134
+[deploying-node-with-spark]: /deploying-node-with-spark
8  articles/connect-it/app.js
... ...
@@ -1,6 +1,6 @@
1 1
 var Connect = require('connect');
2 2
 
3  
-module.exports = Connect.createServer([
4  
-  {module: require('./log-it')},
5  
-  {module: require('./serve-js')}
6  
-]);
  3
+module.exports = Connect.createServer(
  4
+  require('./log-it')(),
  5
+  require('./serve-js')()
  6
+);
16  articles/connect-it/app2.js
... ...
@@ -1,10 +1,10 @@
1 1
 var Connect = require('connect');
2 2
 
3  
-module.exports = Connect.createServer([
4  
-  {filter: "log"}, // Log responses to the terminal using Common Log Format.
5  
-  {filter: "response-time"}, // Add a special header with timing information.
6  
-  {filter: "conditional-get"}, // Add HTTP 304 responses to save even more bandwidth.
7  
-  {filter: "cache"}, // Add a short-term ram-cache to improve performance.
8  
-  {filter: "gzip"}, // Gzip the output stream when the browser wants it.
9  
-  {provider: "static", root: "."} // Serve all static files in the current dir.
10  
-]);
  3
+module.exports = Connect.createServer(
  4
+  Connect.logger(), // Log responses to the terminal using Common Log Format.
  5
+  Connect.responseTime(), // Add a special header with timing information.
  6
+  Connect.conditionalGet(), // Add HTTP 304 responses to save even more bandwidth.
  7
+  Connect.cache(), // Add a short-term ram-cache to improve performance.
  8
+  Connect.gzip(), // Gzip the output stream when the browser wants it.
  9
+  Connect.staticProvider(__dirname) // Serve all static files in the current dir.
  10
+);
10  articles/connect-it/connect-http.js
... ...
@@ -1,8 +1,6 @@
1 1
 var Connect = require('connect');
2 2
 
3  
-Connect.createServer([
4  
-    {module: {handle: function (req, res, next) {
5  
-        // Every request gets the same "Hello Connect" response.
6  
-        res.simpleBody(200, "Hello Connect");
7  
-    }}}
8  
-]).listen(8080);
  3
+Connect.createServer(function (req, res, next) {
  4
+  // Every request gets the same "Hello Connect" response.
  5
+  res.simpleBody(200, "Hello Connect");
  6
+}).listen(8080);
43  articles/connect-it/log-it.js
... ...
@@ -1,28 +1,27 @@
1  
-var sys = require('sys');
  1
+module.exports = function logItSetup() {
2 2
 
3  
-// Initialize the counter
4  
-exports.setup = function setup() {
5  
-  this.counter = 0;
6  
-};
7  
-
8  
-exports.handle = function handle(req, res, next) {
9  
-  var writeHead = res.writeHead; // Store the original function
  3
+  // Initialize the counter
  4
+  var counter = 0;
10 5
   
11  
-  var counter = this.counter++;
  6
+  return function logItHandle(req, res, next) {
  7
+    var writeHead = res.writeHead; // Store the original function
  8
+
  9
+    counter++;
  10
+
  11
+    // Log the incoming request
  12
+    console.log("Request " + counter + " " + req.method + " " + req.url);
12 13
 
13  
-  // Log the incoming request
14  
-  sys.puts("Request " + counter + " " + req.method + " " + req.url);
  14
+    // Wrap writeHead to hook into the exit path through the layers.
  15
+    res.writeHead = function (code, headers) {
  16
+      res.writeHead = writeHead; // Put the original back
15 17
 
16  
-  // Wrap writeHead to hook into the exit path through the layers.
17  
-  res.writeHead = function (code, headers) {
18  
-    res.writeHead = writeHead; // Put the original back
19  
-    
20  
-    // Log the outgoing response
21  
-    sys.puts("Response " + counter + " " + code + " " + JSON.stringify(headers));
22  
-             
23  
-    res.writeHead(code, headers); // Call the original
  18
+      // Log the outgoing response
  19
+      console.log("Response " + counter + " " + code + " " + JSON.stringify(headers));
  20
+
  21
+      res.writeHead(code, headers); // Call the original
  22
+    };
  23
+
  24
+    // Pass through to the next layer
  25
+    next();
24 26
   };
25  
-  
26  
-  // Pass through to the next layer
27  
-  next();
28 27
 };
22  articles/connect-it/serve-js.js
... ...
@@ -1,13 +1,15 @@
1 1
 var fs = require('fs');
2 2
 
3  
-exports.handle = function handle(req, res, next) {
4  
-  // Serve any file relative to the process.
5  
-  // NOTE security was sacrificed in this example to make the code simple.
6  
-  fs.readFile(req.url.substr(1), function (err, data) {
7  
-    if (err) {
8  
-      next(err);
9  
-      return;
10  
-    }
11  
-    res.simpleBody(200, data, "application/javascript");
12  
-  });
  3
+module.exports = function serveJsSetup() {
  4
+  return function serveJsHandle(req, res, next) {
  5
+    // Serve any file relative to the process.
  6
+    // NOTE security was sacrificed in this example to make the code simple.
  7
+    fs.readFile(req.url.substr(1), function (err, data) {
  8
+      if (err) {
  9
+        next(err);
  10
+        return;
  11
+      }
  12
+      res.simpleBody(200, data, "application/javascript");
  13
+    });
  14
+  };
13 15
 };

0 notes on commit 5d335f9

Please sign in to comment.
Something went wrong with that request. Please try again.