Nodejs has a built in OS module that we can use by having this line in our code
var os = require('os');
There are a number of functions to use such as getting free memory, total memory, cpu usage, load average, etc.
My question here is HOW does nodejs calculate this information?
For example, the free/total RAM memory, how is that being done under curtains. Is it calling another process to read stats from the system? is it running a separate command like iostat
or dstat
? How is it actually retrieving that data for us?
The os.totalmem
function is a native function from process.binding('os')
called getTotalMem
. Their implementations can be found in the Node source code:
The following code can be found in src/node_os.cc
:
static void GetTotalMemory(const FunctionCallbackInfo<Value>& args) {
double amount = uv_get_total_memory();
if (amount < 0)
return;
args.GetReturnValue().Set(amount);
}
// ...
env->SetMethod(target, "getTotalMem", GetTotalMemory);
The uv_get_total_memory
function has several implementations based on the host OS.
Here is the Linux implementation deps/uv/src/unix/linux-core.c
:
uint64_t uv_get_total_memory(void) {
struct sysinfo info;
if (sysinfo(&info) == 0)
return (uint64_t) info.totalram * info.mem_unit;
return 0;
}
The Linux build uses sysinfo
to get this information. It does not need to spawn another another process.