当代码在终端中停止工作时,NodeJS console.log(anything)

NodeJS console.log(anything) when the code stops working in terminal

当内存不足时,我的代码会自行停止并给出一堆关于 'out of memory' 的错误。
当我的代码停止工作或我自己停止它 (ctrl+c) 时,有什么方法可以 console.log() 我想要的任何东西吗?

终端一切正常。

好吧,你可以尝试增加 Node.js 的内存限制,方法是:

// Increase max memory to 4GB.
$ node --max-old-space-size=4096 index.js

所以它不会崩溃。

您可以尝试类似的方法:

const os = require('os');

const THRESHOLD = 1000000 * 100; // 100 mb

// Check how much space left with a minute interval
setInterval(function () {
    if (os.freemem() - process.memoryUsage().rss < THRESHOLD) {
        console.log('We lack of memory!');
    }

}, 1000 * 60);