【发布时间】:2014-11-11 13:34:20
【问题描述】:
我正在运行以下 node.js 代码:
var http = require('http');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type': 'text/plain'});
res.write("Hello");
res.end();
}).listen(8888);
当我启动服务器时(通过输入node myFile.js),节点进程正在使用 9MB 内存。
然后我创建了以下网页,我在我的网络浏览器的几个选项卡中打开它,所以我同时向节点发出请求:
<html>
<head>
<script>
var ajax = {};
var questions = [];
var questionsResponses = [];
ajax.x = function() {
if (typeof XMLHttpRequest !== 'undefined') {
return new XMLHttpRequest();
}
var versions = [
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
var xhr;
for (var i = 0; i < versions.length; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
} catch (e) {}
}
return xhr;
};
ajax.send = function(url, callback, method, data, async) {
var x = ajax.x();
x.open(method, url, async);
x.onreadystatechange = function() {
if (x.readyState == 4) {
if (x.status == 200) {
callback(x.responseText)
} else {
//TODO
}
}
};
if (method == 'POST') {
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
x.send(data)
};
ajax.get = function(url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url + '?' + query.join('&'), callback, 'GET', null, async)
};
ajax.post = function(url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, callback, 'POST', query.join('&'), async)
};
var count = 0;
function sayHello(){
ajax.get("http://localhost:8888", {}, sayHello, true);
var heading = document.getElementById("c");
while (heading.firstChild) {
heading.removeChild(heading.firstChild);
}
var countText = document.createTextNode(""+count++);
heading.appendChild(countText);
}
</script>
</head>
<body>
<h1 id="c"></h1>
<script> sayHello();</script>
</body>
</html>
节点现在使用的内存是 46.2 MB。它慢慢增加。每隔一段时间就会有一次跳跃,然后继续缓慢增加。这是节点在同时收到许多请求时的正常行为,还是泄漏?
编辑:似乎稳定在 46.4 MB。但我不知道它是否稳定,因为我发出的请求数量有限(因为我在网络浏览器中打开了多个选项卡),所以这可能只是我的笔记本电脑的限制。呵呵
编辑:即使我一次只发出一个请求(即仅在我的网络浏览器中打开一个选项卡),内存似乎也会增加。此外,即使关闭所有窗口后,使用的内存也不会减少(它保持在 46.4 MB)。
【问题讨论】:
标签: javascript node.js memory-leaks