2014-10-01 63 views
0

我使用nodejs中的流將POST請求中的數據轉換爲大寫。我有兩個代碼片段,一個是工作正常,但另一片斷中表現不同

首先,這是工作的正確影響輸出的函數的位置

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])); 

其次,其輸出爲不同

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])); 

唯一的區別我可以請注意,在第一種情況下,函數是在createServer方法內部定義的,其次是在createServer方法外部定義的。這是他們表現不同還是有其他原因的原因?

回答

1
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()會在每次請求到達時調用,所以它工作的很好。在第二個例子中,你只需要調用這個函數一次,你使用相同的結果。

1

在第一個示例中,您將爲每個請求創建一個新的through()流。

在第二個示例中,您將創建一個through()流,並將其用於每個請求。

相關問題