DEV Community

miku86
miku86

Posted on • Edited on

NodeJS: How To Use The OS Module

Intro

So we installed NodeJS on our machine.

Now we want to learn how to get information about the operating system by using the OS module.

Write a simple script

  • Open your terminal
  • Create a file named index.js:
touch index.js
Enter fullscreen mode Exit fullscreen mode
  • Add this JavaScript code into it:
const { platform, arch, release, totalmem, freemem } = require('os');

console.log(`Your Operating System: ${release()} ${platform()} ${arch()}`);
console.log(`${((freemem() / totalmem()) * 100).toFixed(2)} % of your RAM is free.`);
Enter fullscreen mode Exit fullscreen mode

Note: I use the most used url properties to decrease the complexity of this simple example. To see all the available properties, read the docs of the OS module. There is a lot of cool stuff.


Every line explained

/*
  import the os module & destructure the desired properties/functions
  similar to:
  const os = require('os');
  const { platform, arch, release, totalmem, freemem } = os;
*/ 
const { platform, arch, release, totalmem, freemem } = require('os');

// log some information about the operating system
console.log(`Your Operating System: ${release()} ${platform()} ${arch()}`);

// log some information about the memory (ram) (number is rounded to two decimals)
console.log(`${((freemem() / totalmem()) * 100).toFixed(2)} % of your RAM is free.`);

Enter fullscreen mode Exit fullscreen mode

Run it from the terminal

  • Run it:
node index.js
Enter fullscreen mode Exit fullscreen mode
  • Result:
Your Operating System: 5.2.9-arch1-1-ARCH linux x64
18.63 % of your RAM is free. 

Enter fullscreen mode Exit fullscreen mode

Further Reading


Questions

  • Do you have an interesting idea, what we could create with this module?

Top comments (0)