【发布时间】: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