Nodejs Globals

Nodejs globals are global objects which are available in all modules. These objects are modules and functions and can be used directly. We don’t need to specify them. Below are few mostly used globals.

__dirname –

it represents current or root directory name of the application.

Create a file “node-global.js” with below code.
console.log(" Your application is running in this directory - ", __dirname);

Below SS shows the output of this program.

Node Globals Dirname

__filename –

– it represents the current path of running application

Let’s add below code to “node-global.js.

console.log("Your application filename is -", __filename);	

Below SS shows the output of this program

Node Globals Filename

Console –

it is used to print msg’s / logs in the terminal which can be used for debugging and troubleshooting purpose.. It is used with 3 methods

  1. console.log() – to print the normal logs
  2. console.warn() – to print the warning logs
  3. console.error() – to print the error logs

Buffer and timer –

lets cover these topic in later sections.

Nodejs OS

index Method Description
1 os.arch() It is used for getting CPU arch of OS.
2 os.cpus() It is used to get information about CPU
3 os.endianness() It returns the cpu’s endianness.
4 os.freemem() Returns the sum of free device memory.
5 os.homedir() Returns the sum of free device memory.
6 os.hostname() returns operating system hostname.
7 os.loadavg() returns an array comprising the load averages
8 os.networkinterfaces() This approach returns a list of interfaces at the network.
9 os.platform() Returns OS name.
10 os.release() returns the release of the operating system.
11 os.tmpdir() returns the default directory for temporary files
12 os.totalmem() returns in Bytes the total amount of system memory.
13 os.type() returns the name of the operating system.
14 os.uptime() This method returns uptime for the machine in seconds.

OS is an inbuilt module in node js. In order to use predefined methods of OS, we need to requite os module in our application.

Lets create a file “node-os.js” with below code

var os = require("os");
// cpus
console.log('cpu : ' + os.cpus());
// OS type
console.log('OS type : ' + os.type());
// OS platform
console.log('OS platform : ' + os.platform());
// Total system memory
console.log('total memory in this system: ' + os.totalmem() + " bytes.");
// Total free memory
console.log('free memory available in this system: ' + os.freemem() + " bytes.");	

Below SS shows output of this program.

Node Globals OS

Subscribe Now