The built-in os module in Node provides methods that help you check your machine’s memory size:
- os.totalmem(): Returns the total amount of system memory in bytes.
- freemem(): Returns the amount of free system memory in bytes.
To get the results in MB, you need to divide them by 1024 * 1024 (because 1 MB = 1024 kB and 1kB = 1024 bytes).
Example:
import os from 'os'
// CommonJS require:
// const os = require('os');
// Get the number of total memory in Byte
const totalRAM = os.totalmem();
// Print the result in MB
console.log(totalRAM / (1024 * 1024));
// Get the number of available memory in Byte
const freeRAM = os.freemem();
// Print the result in MB
console.log(freeRAM / (1024 * 1024));
That’s it. Further reading:
- How to Delete a File or Directory in Node.js
- Pagination in TypeORM (Find Options & QueryBuilder)
- Node.js: How to Use “Import” and “Require” in the Same File
- Node.js: Get File Name and Extension from Path/URL
- 7 best Node.js frameworks to build backend APIs
- Top 5 best Node.js Open Source Headless CMS
You can also check out our Node.js category page or PHP category page for the latest tutorials and examples.