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

时间:2015-03-15 07:40:38

标签: javascript node.js http stream pipe

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

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的异步性质的方法,即必须始终首先写入头。

虽然如果没有直接解决流来解决订单问题,我肯定会感谢任何小问题的答案,我想利用这个机会更好地了解它们。有很多类似的情况,但这种情况更多的是打开蠕虫,而不是其他任何东西。

1 个答案:

答案 0 :(得分:1)

让我们在Node.js和.pause() / .resume()流函数中使用回调和流:

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双工流。

注意:它仍然是伪代码