fac*_*ous 8 logging memory-leaks file node.js
我看到内存泄漏,使用以下代码:
while (true) {
console.log("Testing.");
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试定义字符串并只使用常量,但它会泄漏内存,仍然:
var test = "Testing.";
while (true) {
console.log(test);
}
Run Code Online (Sandbox Code Playgroud)
如果我使用文件而不是标准日志,则会发生同样的泄漏:
var test = "Testing.";
var fh = fs.createWriteStream("test.out", {flags: "a"});
while (true) {
fh.write(test);
}
Run Code Online (Sandbox Code Playgroud)
我想也许是因为我没有正确关闭文件,但我尝试了这个并且仍然看到了泄漏:
var test = "Testing";
while (true) {
var fh = fs.createWriteStream("test.out", {flags: "a"});
fh.end(test);
fh.destroy();
fh = null;
}
Run Code Online (Sandbox Code Playgroud)
有没有人有任何关于如何在没有泄漏记忆的情况下写东西的提示?
the*_*ejh 10
发生这种情况是因为您永远不会让节点有机会处理"写入成功"事件,因此它们会无休止地排队.为了让节点有机会处理它们,你必须让事件循环不时地进行一次迭代.这不会泄漏:
function newLine() {
console.log("Testing.");
process.nextTick(newLine);
}
newLine();
Run Code Online (Sandbox Code Playgroud)
在实际使用案例中,这不是问题,因为您几乎不必一次写出如此大量的数据.如果是这样,请不时循环事件循环.
然而,还有第二个问题也出现了这个nextTick
诀窍:写入是异步的,如果控制台/文件/什么比节点慢,节点无休止地缓冲数据,直到输出再次空闲.为了避免这种情况,你必须drain
在写完一些东西之后听这个事件 - 它告诉你管道什么时候再空闲.见这里:http://nodejs.org/docs/latest/api/streams.html#event_drain_
归档时间: |
|
查看次数: |
2118 次 |
最近记录: |