为什么响应已closures而未完成?
我在函数readFile
中的node.js中有以下代码:
res.setHeader("content-type", 'application/octet-stream'); res.setHeader("Content-Disposition", 'attachment; filename="' + 'original' + '"' + "; filename*=UTF-8''" + 'original' + ""); var readStream; var exists = fs.existsSync(fullPath); if (exists) { callback(true); readStream = fs.createReadStream(fullPath); readStream.pipe(res); } else { callback(false); return; } res.on('finish', function(){ logger.info('response ending'); readStream.close(); }) res.on('close', function(){ logger.info('response close'); readStream.close(); }) res.on('error', function(error){ logger.info(error); readStream.close(); })
出于某种原因,一些请求发出close
事件,而其他的finish
。 据我了解,当出现问题时会close
。
closures事件可以在2秒到2分钟之间发射。 在极less数情况下,不会发出close
和未finish
事件,并且所有请求都“卡住”,等待响应。
有些请求会成功,其他原因是什么?
编辑
我怎么知道为什么一个closures事件已经发出? 这是客户端问题还是我的应用程序中的错误?
如果有一个finish
那么这是一切正常,但如果有一个close
那么可能是因为任何事情。 在pipe道完成之前,我尝试了下面的代码来处理事件声明。
1. `res.emit('close');` And 2. `readStream.close();`
现在,第一个显式地发出closures事件,第二个closures被pipe理的readStream。 这两个语句都会触发res.on('close')
,但是我找不到close
的原因。
我不能确定它是一个服务器错误还是客户端错误,但可能有以下原因:
-
res.emit('close');
明确发出closures事件。 -
pipe源问题出了问题。 (例如在上面的例子#2中,readStream被closures了),在这种情况下,会比其余的原因花费更长的时间。
-
响应发送开始后,networking发生故障
-
客户端也可能导致closures事件触发,如果它请求数据,然后客户端不存在接收数据。
原因可能是任何事情,这使得答复不完整。
我认为这来自HTTP协议本身。 有一个保持活着的选项。 如果使用了这个连接,那么连接可以被重用于不同的请求。
你closuresres.set("Connection", "close");
ant再次testing一下。
我宁愿结束你的回应,当close和finish事件被调用,而不是closuresreadStream。
res.setHeader("content-type", 'application/octet-stream'); res.setHeader("Content-Disposition", 'attachment; filename="' + 'original' + '"' + "; filename*=UTF-8''" + 'original' + ""); var readStream; var exists = fs.existsSync(fullPath); if (exists) { callback(true); readStream = fs.createReadStream(fullPath); readStream.pipe(res); } else { callback(false); return; } res.on('finish', function(){ logger.info('response ending'); readStream.close(); // This closes the readStream not the response res.end('FINISHED'); // Ends the response with the message FINISHED }) res.on('close', function(){ logger.info('response close'); readStream.close(); // This closes the readStream not the response res.end('CLOSED'); // Ends the response with the message CLOSED }) res.on('error', function(error){ logger.info(error); readStream.close(); // This closes the readStream not the response res.end(error); // Ends the response with ERROR })
由于closures了只closuresreadStream而不是响应的readStream,所以响应没有closures。 要使用res.end()
完成或结束响应。
参考: http : //nodejs.org/api/http.html#http_event_close_1 http://nodejs.org/api/http.html#http_response_end_data_encoding
希望这可以帮助。
- Node.JS:Azure不会从package.json安装新的依赖项
- NodeJS 100%cpu使用率 – epoll_wait
- Karma:(SystemJS)XHR错误(404 Not Found)加载src / node_modules / angular2-jwt / angular2-jwt.js
- NodeJS + Mongo:插入如果不存在,否则 – 更新
- 玉石中的迭代循环不能正确渲染数据
- 如何在Node.js中设置一个variables为morgan的结果(不logging在控制台上)
- 错误,当我部署ng build –prod Angular 4.3.2
- 使用节点设置Windows PATHvariables?
- node.js代码完成/智能感知