如何处理代码(node.js)中的“进程内存不足后返回的API致命错误处理程序”?

时间:2019-07-10 06:31:33

标签: javascript node.js exception memory-leaks signals

下面是一个玩具程序,我正在使用该程序将进程抛出内存不足异常。

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();

我正在像上面的节点--max-old-space-size =“ 4” index.js`那样运行内存最大为4 mb的程序。 如预期的那样,该程序最终将耗尽内存,引发异常,如下所示:

*#
# 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.

在进程即将或即将用尽内存时,通常我需要一个处理程序

1 个答案:

答案 0 :(得分:0)

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

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