I'm using this method of Node.js Os module: os.freemem()
This is my sample code:
const os = require('os');
const bytesToSize = (bytes) => {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};
console.log('free memory : ', bytesToSize(os.freemem()));
console.log('total memory : ', bytesToSize(os.totalmem()));
after I run my code, I give the below result:
free memory : 164 MB
total memory : 8 GB
but my OS system monitor show me:
Why is there such a difference?
I'm using this method of Node.js Os module: os.freemem()
This is my sample code:
const os = require('os');
const bytesToSize = (bytes) => {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};
console.log('free memory : ', bytesToSize(os.freemem()));
console.log('total memory : ', bytesToSize(os.totalmem()));
after I run my code, I give the below result:
free memory : 164 MB
total memory : 8 GB
but my OS system monitor show me:
Why is there such a difference?
Share Improve this question asked Aug 18, 2018 at 19:19 Saeed JalaliSaeed Jalali 4364 silver badges17 bronze badges 1-
you are mixing data measurement... 1 KB = 1000 bytes. 1 KiB = 1024. Your sizes array should be
['Bytes', 'KiB', 'MiB', 'GiB', 'TiB']
if you are using 1024 – Endless Commented Aug 18, 2018 at 19:33
2 Answers
Reset to default 7Apparently system monitor doesn't show you the free memory, but the available one.
Node's OS.freemem()
and free
mand use the information from /proc/meminfo
:
klaimmore@klaimmore-HP-ZBook-14:/rep$ sudo cat /proc/meminfo | grep Mem
MemTotal: 16320372 kB
MemFree: 1274072 kB
MemAvailable: 10618284 kB
klaimmore@klaimmore-HP-ZBook-14:/rep$ node -p "require('os').freemem()/1024"
1254828
klaimmore@klaimmore-HP-ZBook-14:/rep$ free -k
total used free shared buff/cache available
Mem: 16320372 4684776 1273228 678996 10362368 10617452
Swap: 2097148 0 2097148
Even though, it is true, and node.js returns "free" memory only, it does not make a lot of sense for macOS.
If you really need to access "available" memory, you may use the following package:
https://www.npmjs./package/osx-extra
const osX = require("osx-extra");
const freeMem = osX.freemem();
this package provides freemem() method that returns the actual available memory for macOS and fallbacks to the same freemem() methods from node:os
core module for other operating systems.