Node.js os.totalmem() Method

The os.totalmem() method is an inbuilt application programming interface of the os module which is used to get the amount of total system memory in bytes. 

Syntax:

os.totalmem()

Parameters: This method does not accept any parameters. 

Return Value: This method returns an integer value that specifies the amount of total system memory in bytes. 

Example 1: The below example illustrates the use of os.totalmem() method in Node.js: 

javascript




// Node.js program to demonstrate the   
// os.totalmem() method
 
// Import the os module
const os = require('os');
 
// Printing os.totalmem() method value
console.log(os.totalmem());


Output:

8502722560

Example 2: The below example illustrates the use of the os.totalmem() method in Node.js: 

javascript




// Node.js program to demonstrate the   
// os.totalmem() method
 
// Import the os module
const os = require('os');
 
// Convert total memory to kb, mb and gb
const total_memory = os.totalmem();
const total_mem_in_kb = total_memory / 1024;
const total_mem_in_mb = total_mem_in_kb / 1024;
const total_mem_in_gb = total_mem_in_mb / 1024;
 
total_mem_in_kb = Math.floor(total_mem_in_kb);
total_mem_in_mb = Math.floor(total_mem_in_mb);
total_mem_in_gb = Math.floor(total_mem_in_gb);
 
total_mem_in_mb = total_mem_in_mb % 1024;
total_mem_in_kb = total_mem_in_kb % 1024;
total_memory = total_memory % 1024;
 
// Display memory size
console.log("Total memory: " + total_mem_in_gb + "GB "
    + total_mem_in_mb + "MB " + total_mem_in_kb
    + "KB and " + total_memory + "Bytes");


Output:

Total memory: 7GB 940MB 848KB and 0Bytes

Example 3: The below example illustrates the use of the os.totalmem() method in Node.js: 

javascript




// Node.js program to demonstrate the   
// os.totalmem() method
 
// Import the os module
const os = require('os');
 
// Printing free memory out of total memory
console.log("Free Memory " + String(os.freemem())
    + " Bytes out of " + String(os.totalmem()) + " Bytes");


Output:

Free Memory 4161896448 Bytes out of 8502722560 Bytes

Note: The above program will compile and run by using the node index.js command.

Reference: https://nodejs.org/api/os.html#os_os_totalmem



Contact Us