簡體   English   中英

在Node.js中使用流來緩沖HTTP通信

[英]Using streams in Node.js to buffer HTTP communications

我正在嘗試使用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的異步特性,即必須始終首先編寫標頭。

盡管我肯定會喜歡用很少的技巧來解決訂單問題而無需直接解決流問題的任何答案,但我想借此機會更好地了解它們。 有很多類似的情況,但是這種情況比其他任何事情更容易打開蠕蟲的罐頭。

讓我們在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雙工流。

注意:它仍然是偽代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM