ujjwalwahi
ujjwalwahi

Reputation: 342

Position of function affecting output

I am converting data in POST request to upper case using streams in nodejs. I have two code snippets, one is working fine, but another snippet is behaving differently

First, which is working correct

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 a POST\n');
    });
server.listen(parseInt(process.argv[2]));

Second, whose output is different

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('Send me a post\n');
}
});
server.listen(parseInt(process.argv[2]));

Only difference I can notice is that in first case function is defined inside createServer method and in second it is defined outside createServer method. Is this is the reason that they are behaving differently or there is any other reason?

Upvotes: 0

Views: 36

Answers (2)

lutaoact
lutaoact

Reputation: 4429

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 a POST\n');
    });

through() will invoke every time when your request comes, so It works well. On the seconde example, you just calll this function one time, you use the same result.

Upvotes: 1

SLaks
SLaks

Reputation: 887957

In the first example, you create a new through() stream for each request.

In the second example, you create a single through() stream and use it for every request.

Upvotes: 1

Related Questions