Ниже представлена игрушечная программа, которую я использую для исключения процесса из памяти.
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 Мб, как этот узел --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.
В основном мне нужен обработчик, когда процесс уходит или собирается выйти из памяти