在Node.js中使用stream缓冲HTTP通信

我试图在Node.js中使用stream,基本上build立一个正在运行的HTTP数据缓冲区,直到一些处理完成,但我正在努力的stream的细节。 一些伪代码可能会帮助:

var server = http.createServer(function(request, response) { // Create a buffer stream to hold data generated by the asynchronous process // to be piped to the response after headers and other obvious response data var buffer = new http.ServerResponse(); // Start the computation of the full response as soon as possible, passing // in the buffer stream to hold returned data until headers are written beginAsyncProcess(request, buffer); // Send headers and other static data while waiting for the full response // to be generated by 'beginAsyncProcess' sendObviousData(response, function() { // Once obvious data is written (unfortunately HTTP and Node.js have // certain requirements for the order data must be written in) then pipe // the stream with the data from 'beginAsyncProcess' into the response buffer.pipe(response); }); }); 

大部分这是几乎合法的代码,但它不起作用。 基本的问题是,当存在与HTTP请求相关的特定顺序要求时,要想办法利用Node.js的asynchronous特性,即首先必须首先写入。

虽然我一定会很欣赏任何答案,而不需要直接处理stream,就可以绕过订单问题,我希望借此机会更好地了解它们。 有很多类似的情况,但是这种情况更多的是打开蠕虫的jar头。

让我们在Node.js和.pause() / .resume()stream函数中使用callback和stream:

 var server = http.createServer(function(request, response) { // Handle the request first, then.. var body = new Stream(); // <-- you can implement stream.Duplex for read / write operations body.on('open', function(){ body.pause(); // API generate data // body.write( generated data ) <-- write to the stream body.resume(); }); var firstPartOfThePage = getHTMLSomeHow(); response.writeHead(200, { 'Content-Type': 'text/html'}); response.write(firstPartOfThePage, function(){ // <-- callback after sending first part, our body already being processed body.pipe( response ); // <-- This should fire after being resumed body.on('end', function(){ response.end(); // <-- end the response }); }); }); 

检查这个: http ://codewinds.com/blog/2013-08-31-nodejs-duplex-streams.html为costum双工stream创作。

注意:这仍然是一个伪代码