In this article, we will discuss the core nodejs components available in global or current module. How to get file and directory name in node js. Node JS console object and its use.

Console

console object is a global object available in node js and frontend js. In frontend, console object is used to print data in browser console window and to debug js in browser.

console.log

console.log method is used to log output in console.

Hello Node


    console.log("Hello Node");    
    

2 3


    var x=2, y=3;
    console.log(x,y);    
    

console.error

console.error method is used to print error messages in console.

error found


    console.error("error found");    
    

String Substitution

To substitute strings in console, use %s.

hi avi, how are you?


    var x=2, y=3;
    console.log("hi %s, how are you?","avi");    
    

Numbers Substitution

To substitute numbers in console, use %d.

x is 2 and y is 3.


    console.log("x is %d and y is  %d.",2,3);    
    

Style console output

To add style to console, use %c and add css properties in second argument.

This is red


    console.log("This is %cred","color:red");    
    

This is highligted text


    console.log("This is %chighligted text","background:yellow");    
    

Filename

To get file name in node js, we use __filename variable. This variable is available in all files we are working.

Get filename in MacOS

/Users/avinashmalhotra/Desktop/node/src/path.js
         
    console.log(__filename);
    

Get filename in Window OS

C:\Users\avinashmalhotra\Desktop\node\src/path.js
         
    console.log(__filename);
    

Dirname

To get directory name in node js, we use __dirname variable. This variable is also available in all directories we are working.

Get directory name in MacOS

/Users/avinashmalhotra/Desktop/node/src
         
    console.log(__dirname);
    

Get directory name in Window OS

C:\Users\avinashmalhotra\Desktop\node\src
         
    console.log(__dirname);
    

Global

Node js global object is same like window object in frontend js. Some popular global properties are console, setTimeout, setInterval etc.

         
console.log( console===global.console)// true 
console.log( setInterval===global.setInterval)// true 
console.log( setInterval===global.setInterval)// true 
console.log( process===global.process)// true 
  
    

Add property to global

We can also add properties and methods to global object to make it available everywhere in our node application.

avi
         
    global.name="avi";
    console.log(global.name);
    

global using other file

     /* global.js */
global.name="avi";
global.id=212;                          
     /* app.js */
require('./global');
console.log(global.name ) // avi
console.log(global.id ) // 212