【问题标题】:How to handle 'API fatal error handler returned after process out of memory' in code (node.js)?如何在代码(node.js)中处理“进程内存不足后返回的 API 致命错误处理程序”?
【发布时间】:2019-07-10 06:31:33
【问题描述】:

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

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

我正在运行内存上限为 4 mb 的程序,例如这个节点 --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.

通常我需要一个处理程序,当进程运行或即将耗尽内存时

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-04-22
      • 2018-12-06
      • 2021-03-01
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多