Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了node.js – nodejs中console.log的循环大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的MCVE如下

@H_403_11@var i = 0; for(;;) console.log(i++)

当我这样做时,在某个时刻,我的nodejs只是停止打印东西,给我一个看起来像这样输出

@H_403_11@[...] 684665 684666 684667

然后,我得到了这个:

@H_403_11@<--- Last few GCs ---> 69097 ms: Scavenge 1397.2 (1456.7) -> 1397.2 (1456.7) MB,0.8 / 0 ms (+ 1.7 ms in 1 steps since last GC) [alLOCATIOn failure] [incremental marking delaying mark-sweep]. 70462 ms: Mark-sweep 1397.2 (1456.7) -> 1396.0 (1456.7) MB,1364.9 / 0 ms (+ 2.8 ms in 2 steps since start of marking,biggest step 1.7 ms) [last resort gc]. 71833 ms: Mark-sweep 1396.0 (1456.7) -> 1397.1 (1456.7) MB,1370.2 / 0 ms [last resort gc]. <--- JS stacktrace ---> ==== JS stack trace ========================================= Security co@R_618_10443@t: 0xcdf79d37399 <JS Object> 1: formatPrimitive(aka formatPrimitivE) [util.js:~411] [pc=0x634d9f4113f] (this=0xcdf79d04131 <undefined>,ctx=0x17b18f4d561 <an Object with map 0x32fd25043ef9>,value=16248021) 2: formatValue(aka formatvalue) [util.js:223] [pc=0x634d9f1fdbb] (this=0xcdf79d04131 <undefined>,value=16248021,recurseTimes=2) 3: inspect(aka inspect) [uti... Fatal error: Call_AND_RETRY_LAST AlLOCATIOn Failed - process out of memory [1] 19446 abort (core dumped) node

我想知道,console.log可以做什么导致内存不足错误

解决方法

根据这个讨论: https://groups.google.com/forum/#!topic/nodejs/KtONbpVV68U

每次调用console.log(或其他日志记录方法)时,控制台对象都会分配一些内存.垃圾收集器在下一个滴答时将释放该内存.但是如果你有一个太大的循环,那么下一个勾号永远不会到来.

但我测试了这个:

@H_403_11@seTinterval(function() { for (var i = 0; i < 100000; ++i) { console.log(i); } },10000)

根据谷歌小组讨论,在每个间隔之间,NodeJS垃圾收集器应该通过console.log释放分配的内存.但事实并非如此.每次循环运行时,我的进程占用更多内存.

我也测试了这个:

@H_403_11@var fs = require('fs') var output = fs.createWriteStream('./stdout.log'); var errorOutput = fs.createWriteStream('./stderr.log'); var logger = new console.Console(output,errorOutput); var i = 0; for (;;) { logger.log(i++); }

行为是一样的.这个过程需要越来越多的RAM,直到它崩溃(因为没有更多的RAM可用).并且文件stdout.log始终为空.

最后,我测试了这个:

@H_403_11@var fs = require('fs') var output = fs.createWriteStream('./stdout.log'); var errorOutput = fs.createWriteStream('./stderr.log'); var logger = new console.Console(output,errorOutput); seTinterval(function() { for (var i = 0; i < 100000; i++) { logger.log(i); } },5000)

这个例子很有趣.因为在每个间隔之间写入了stdout.log(行被附加到文件中),并且进程回收的RAM不会增长.垃圾收集器在每个间隔之间完成其工作.

我认为控制台对象不能很好地处理缓冲区.但它仍然很奇怪.如果你使用标准输出(只有一个console.log),它看起来控制台对象保持在目前为止打印的内存中.它永远不会被清洗.如果你使用文件输出,一切正常(当然,除非你在无限循环中写它).

也许是因为NodeJS版本,我正在使用NodeJS 0.12.7

大佬总结

以上是大佬教程为你收集整理的node.js – nodejs中console.log的循环全部内容,希望文章能够帮你解决node.js – nodejs中console.log的循环所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。