get system total memory in typescript

You can use the os module in Node.js to get System Information including Total Memory. Here's an example code snippet:

index.ts
import os from 'os';

const totalMemory = os.totalmem();
console.log(`Total Memory: ${totalMemory} bytes`);
108 chars
5 lines

The os.totalmem() method returns the total amount of system memory in bytes.

If you want to convert the bytes to a more human-readable format, you can create a helper function like this:

index.ts
function formatBytes(bytes: number, decimals = 2) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

const totalMemory = os.totalmem();
console.log(`Total Memory: ${formatBytes(totalMemory)}`);
451 chars
12 lines

This will output the total memory in a human-readable format, such as "8.00 GB".

gistlibby LogSnag