Permalink
Browse files

Added sys.pump() stream example

  • Loading branch information...
1 parent 732ee7a commit c3bbdffdc91b872e09ebaaf051afe7da917f021c @tj tj committed Aug 15, 2010
Showing with 54 additions and 2 deletions.
  1. +26 −2 chapters/streams.md
  2. +16 −0 src/streams/echo.js
  3. +12 −0 src/streams/pump.js
View
@@ -11,10 +11,34 @@
// Do something with the Buffer
});
-As we know, we can call `toString()` on a buffer to return a string, however in the case of streams if desired we may call `setEncoding()` on the stream,
+As we know, we can call `toString()` a buffer to return a string representation of the binary data, however in the case of streams if desired we may call `setEncoding()` on the stream,
after which the _data_ event will emit strings.
req.setEncoding('utf8');
req.on('data', function(str){
// Do something with the String
- });
+ });
+
+Another import event is the _end_ event, which represents the ending of _data_ events. For example below we define an HTTP echo server, simply "pumping" the request body data through to the response. So if we **POST** "hello world", our response will be "hello world".
+
+ var http = require('http');
+
+ http.createServer(function(req, res){
+ res.writeHead(200);
+ req.on('data', function(data){
+ res.write(data);
+ });
+ req.on('end', function(){
+ res.end();
+ });
+ }).listen(3000);
+
+The _sys_ module actually has a function designed specifically for this "pumping" action, aptly named `sys.pump()`, which accepts a read stream as the first argument, and write stream as the second.
+
+ var http = require('http'),
+ sys = require('sys');
+
+ http.createServer(function(req, res){
+ res.writeHead(200);
+ sys.pump(req, res);
+ }).listen(3000);
View
@@ -0,0 +1,16 @@
+
+/**
+ * Module dependencies.
+ */
+
+var http = require('http');
+
+http.createServer(function(req, res){
+ res.writeHead(200);
+ req.on('data', function(data){
+ res.write(data);
+ });
+ req.on('end', function(){
+ res.end();
+ });
+}).listen(3000);
View
@@ -0,0 +1,12 @@
+
+/**
+ * Module dependencies.
+ */
+
+var http = require('http'),
+ sys = require('sys');
+
+http.createServer(function(req, res){
+ res.writeHead(200);
+ sys.pump(req, res);
+}).listen(3000);

0 comments on commit c3bbdff

Please sign in to comment.