• Node.js Video Tutorials

Node.js - os.freemem() Method



The os module of Node.js provides a bunch of operating system-related utility methods and properties. In this chapter, we are going to learn the os.freemem() method of the os module with appropriate examples.

The Node.js os.freemem() method will return the amount of free memory left in the RAM of the current computer in bytes as an integer. This value will always be less than totalmem, which returns the total system memory in bytes. The returned value can be useful for determining if a process needs more memory or if it should scale back its operations due to lack of resources.

Syntax

Following is the syntax of the Node.js os.freemem() method −

os.freemem()

Parameters

This method does not accept any parameters.

Return value

This method will return the amount of free system memory in bytes as an integer value.

Following is the conversion chart −

  • 1024 bytes = 1KB (Kilobyte)

  • 1024 KB = 1 MB (Megabyte)

  • 1024 MB = 1 GB (Gigabyte)

  • 1024 GB = 1 TB (Terabyte)

  • 1024 TB = 1 PB (Petabyte)

Example

In the following example, we are trying to print the free space of the current system by using the os.freemem() method.

const os = require('os');
console.log(os.freemem());

Output

130521513984

Note − To get the accurate result, better execute the above code in local.

If we compile and run the above program, the os.freemem() returns the free system memory available of the current computer in bytes.

9211826176

Example

In the example below, we are trying to convert the amount of free system memory from bytes to KB(Kilobyte), MB(Megabyte), and GB(Gigabyte).

const os = require('os');
var mem_in_bytes = os.freemem();
var mem_in_kb = Math.floor(os.freemem()/(1024));
var mem_in_mb = Math.floor(os.freemem()/(1024*1024));
var mem_in_gb = Math.floor(os.freemem()/(1024*1024*1024));

console.log("The amount of free current system memory(in bytes): " + mem_in_bytes);
console.log("The amount of free current system memory(in KB): " + mem_in_kb); 
console.log("The amount of free current system memory(in MB): " + mem_in_mb); 
console.log("The amount of free current system memory(in GB): " + mem_in_gb);

Output

The amount of free current system memory(in bytes): 130537541632
The amount of free current system memory(in KB): 127478068
The amount of free current system memory(in MB): 124490
The amount of free current system memory(in GB): 121

Note − To get the accurate result, better execute the above code in local.

If we compile and run the above program, we printed the free system memory in bytes, kilobytes(KB), Megabytes(MB), and Gigabytes(GB).

The amount of free current system memory(in bytes): 9202073600
The amount of free current system memory(in KB): 8986400
The amount of free current system memory(in MB): 8775
The amount of free current system memory(in GB): 8
nodejs_os_module.htm
Advertisements