Node.js streaming adventure lesson 6: declaring a variable vs. in-line function declaration -


learning node.js, nodeschool.io , i'm confused differences between following 2 code segments. difference fundamental node.js or js in general, i'm hoping expert can clarify me.

the accepted answer lesson 6 following. notice through(...) piped in-line.

var http = require('http'); var through = require('through');  var server = http.createserver(function (req, res) {     if (req.method === 'post') {         req.pipe(through(function (buf) {             this.queue(buf.tostring().touppercase());         })).pipe(res);     }     else res.end('send me post\n'); }); server.listen(parseint(process.argv[2])); 

my solution (which fails) declare variable tr so:

var http = require('http'); var through = require('through');  var tr = through(function(buf) {     this.queue(buf.tostring().touppercase()); });  var server = http.createserver(function (req, res) {     if (req.method == 'post') {         req.pipe(tr).pipe(res);     }     else res.end(); }).listen(process.argv[2]); 

why these 2 code blocks produce different results?

the fundamental difference between version of code , version suggested right solution in version create through stream once, means works first time call it, , second time request, stream exhausted (i.e. has reached end previous invocation) , blocks since never reach end again.

thus, need new through stream every time. instance, not have had problem, if had written way:

var http = require('http'); var through = require('through');  var tr = function(){     return through(function(buf) {         this.queue(buf.tostring().touppercase());     }); };  var server = http.createserver(function (req, res) {     if (req.method == 'post') {         req.pipe(tr()).pipe(res);     }     else res.end(); }).listen(process.argv[2]); 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -