在 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);
});
});
其中大部分几乎是合法的代码,但它不起作用。基本问题是找到一种方法来利用 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 双工流。
注意:它仍然是伪代码
相关文章:
- Meteor如何接收HTTP请求
- 在我的情况下,如何进行http请求
- //而不是在src=“”上使用http://"属性
- 我无法使用angularJs($http)访问服务器
- AJAX简单错误.XMLHttpRequest无法加载http://localhost/mpl/getPage.php.
- 如何将PHP get查询转换为Meteor's HTTP.get()
- 角度异步http自动完成
- 什么's本地node.js服务器和python简单http服务器之间的区别
- 角度http服务器页面刷新404s
- http.listen()在运行时接受终端命令
- IIS动态HTTP响应标头
- spring和angularJS(我得到了类似HTTP状态404的错误)
- 存储$http如何从$http函数(Angularjs)外部获取可访问变量中的响应
- Typescript angularjs$http获取响应类型(避免使用<any>)
- 如何从HTTP上下文对象中获取Post数据
- 使用插件收听Firefox标签的http请求
- "访问控制允许起源”;通过javascript从http页面调用同一网站的httpsurl时出现问题
- Meteor HTTP调用出现问题
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- 在 Node.js 中使用流来缓冲 HTTP 通信