如何在代码中处理 'API fatal error handler returned after process out of memory' (node.js)?

How to handle 'API fatal error handler returned after process out of memory' in code (node.js)?

下面是我用来抛出进程内存不足异常的小程序。

function alloc (size) {
    const numbers = size / 8;
    const arr = []
    arr.length = numbers; // Simulate allocation of 'size' bytes.
    for (let i = 0; i < numbers; i++) {
        arr[i] = i;
    }
    return arr;
};

const allocations = []; 

function allocToMax () {

    console.log("Start");

    const field = 'heapUsed';
    const mu = process.memoryUsage();
    console.log(mu);
    const gbStart = mu[field] / 1024 / 1024 / 1024;
    console.log(`Start ${Math.round(gbStart * 100) / 100} GB`);

    let allocationStep = 100 * 1024;

    while (true) {

        const allocation = alloc(allocationStep);

        allocations.push(allocation);

        const mu = process.memoryUsage();
        const mbNow = mu[field] / 1024 / 1024 / 1024;
        console.log(`Total allocated       ${Math.round(mbNow * 100) / 100} GB`);
        console.log(`Allocated since start ${Math.round((mbNow - gbStart) * 100) / 100} GB`);
    }
};

process.on('exit','SIGINT','', function() {
    console.log("tata");
});

allocToMax();

我是运行像这个节点一样内存上限为4mb的程序--max-old-space-size="4" index.js`。 正如预期的那样,该程序最终将超出内存并抛出如下所示的异常

*#
# Fatal error in , line 0
# API fatal error handler returned after process out of memory
#*
or 
*FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory**
I am trying to detect the SIGNAL or anything else in code the process emits in case of Memory leak or FATAL ERROR so that I can perform a graceful exit and restart the server.

大多数时候我需要一个处理程序,当进程运行或即将耗尽内存时

使用 pm2-runtime 服务器会自动重启,而不会杀死 docker。

http://pm2.keymetrics.io/docs/usage/docker-pm2-nodejs/