To have a concrete implementation as matthewmatician mentioned.
You can easily do this all within node by periodically checking your memory usage: https://nodejs.org/api/process.html#process_process_memoryusage. If this is a long-running server, check it every hour or so. Then just fire off an email with a package like nodemailer if the memory reaches a certain threshold.
I like PM2, yet I was wondering if it could be done without.
As noted here, RSS (Resident Set Size) is the full memory usage of the process, this includes all memory usage of the shared memory. RSS can therefore be considered inacurate to be taken as the memory usage of a single process, since the shared memory is also used by other processes. Therefore PSS exists, which divides the shared memory over all other processes used.
I suppose we want to know the PSS value if we want to display the most accurate usage of memory by the node process. However, some person did mention PSS is more important for huge amount of fork processes, such as an Apache server (and thus a lot of shared memory).
var hour = 3600*1000;
var checkMemory = function() {
// Retrieves the memory usage
var memory = process.memoryUsage();
var rss_memory_in_bytes = m.rss;
var rss_memory_in_megabytes = m.rss / (1024**2);
if (rss_memory_in_megabytes > 50) {
// More than 50 megabytes RSS usage, do something
doSomething();
}
}
var doSomething = function() {
// For instance sending an email
}
// Check the memory usage every hour
setInterval(checkMemory, hour);
-- UPDATED --
If there is more heap storage required, the Node process will attempt to allocate this memory. This allocation is done automatically. When successfull the heap storage increases and the rss as well. The heapUsage and heapTotal can therefore be neglected in our case.
There are ways of setting a memory limit, but we are interested at checking for a limit. I think it is reasonable to check for the amount of free system memory left. Yet, this has nothing to do with the actual memory usage of the Node process itself and would require a different threat on how to check for free system memory with a Node script.