我正在尝试在 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);
});
});
其中大部分几乎是合法的代码,但它不起作用。基本问题是找到一种方法来利用 Node 的异步特性.js当存在与 HTTP 请求相关的某些顺序要求时,即标头必须始终首先写入。
虽然我肯定会感谢任何带有小技巧的答案,以便在不直接解决流的情况下解决订单问题,但我想利用这个机会更好地了解它们。有很多类似的情况,但这种情况更多的是打开蠕虫的罐头,而不是其他任何事情。
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 双工流。
注意:它仍然是伪代码