标题可能取的不准确,描述下问题: 最近做了一个系统内包含一个下载.zip 文件的功能,单个文件很小,最多就几百 kb
现在发现在 /proc/pid/fd 下的句柄数量不断增多,但是我自己在测试服上测试了下,又没有重现,不管怎么下载,都没有下载相关的句柄停留,不知道什么问题
下载代码如下:
let mime = "text/plain";
let file_path = path.join('..gm/', process.cwd(), 'uploads', file_name);
fs.exists(file_path, function (exists) {
if (!exists) {
message.setCode(CODE.OBJECT_NOT_EXIST);
return message.send();
}
//获得文件信息
fs.stat(file_path, function (err, stats) {
if (err) {
message.setCode(CODE.FAIL);
return message.send();
}
let content = fs.createReadStream(file_path, {flags: 'r'});
res.writeHead(200, {
'Content-Type': mime,
"Content-Length": stats.size,
'Content-Disposition': 'attachment; filename=' + file_name
});
content.pipe(res);
content.on('end', function () {
res.end();
});
});
});
贴部分句柄数据
72 -> /home/ec2-user/gm/uploads/respatch_scorequest_android_a.zip
73 -> /home/ec2-user/gm/uploads/cpatch_scorequest_android_a.zip
74 -> /home/ec2-user/gm/uploads/respatch_scorequest_android_a.zip
75 -> /home/ec2-user/gm/uploads/cpatch_scorequest_android_b.zip
76 -> /home/ec2-user/gm/uploads/respatch_scorequest_android_a.zip
77 -> /home/ec2-user/gm/uploads/bpatch_scorequest_android_a.zip
78 -> /home/ec2-user/gm/uploads/bpatch_scorequest_android_a.zip
79 -> /home/ec2-user/gm/uploads/respatch_scorequest_android_a.zip
1
forcecharlie 2018-07-19 18:30:59 +08:00 1
One important caveat is that if the Readable stream emits an error during processing, the Writable destination is not closed automatically. If an error occurs, it will be necessary to manually close each stream in order to prevent memory leaks.
https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options 如果下载中断了就会出现这种情况。下载中断需要手动关闭。 |
2
imherer OP @forcecharlie 首先感谢回复
之前确实没有监听 error 事件,但是昨晚加上监听 error 事件后,在 error 里手动 content.destroy();了,而且也打了 log,跑了一晚上问题依旧存在,log 里也无任何信息,说明一直没触发 error 事件 不过我复现了这个 bug,不过复现是操作是 fs.createReadStream(file_path, {flags: 'r', autoClose: false}); 即手动设置 autoClose 为 false,end 之后不 destroy,这个句柄就会一直保持 |