NodeJS - SPLessons

Node.js Global Objects

Home > Lesson > Chapter 7
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Node.js Global Objects

Node.js Global Objects

shape Introduction

Node.js Global Objects are the objects which are built in node globally and are truly global, few objects are not actually global scope but in the module scope and this objects can be accessed from anywhere and are accessible in all the modules.
  • Global
  • Process
  • Console
  • Modules

Global

shape Description

In Node.js programing the global objects can be accessible anywhere and these objects can be used directly instead of including in the applications. The top-level variable is not the global scope. In a browser the global scope is a top-level property by which the var var_name is defined with in the browser and Following are few objects in Node.js. __dirname - The object gives the working directory name where the current executing scripts located. The code below is used to show the current working directory. [c]console.log( __dirname );[/c] Create a file with the above command (assume the file name as dir.js) and compile the file using the below command. [c]$ node dir.js[/c] By compiling the file with the above command one can get the output as shown in the image below. __filename - The object gives the file name of the executed code which is a perfect path of code file and it is not mandatory to use the similar file name in the command line. The code below is used to show the executed code file name. [c] console.log(__filename);[/c] Create a file with the above command (assume the file name as dir.js) and compile the file using the below command. [c]$ node dir.js[/c] By compiling the file with the above command one can get the output as shown in the image below. setInterval(cb, ms) - A function cb is called repeatedly at a particular intervals in ms(milliseconds) using setInterval methods. The interval range should be included between 1-2, 147, 483 and 647 whenever the value not in a range then the interval get changed to 1 milliseconds. The snippet code below demonstrate printing a given string for every 500 milliseconds. [c]setInterval(function(){ console.log('SPLessons Online Tutorials') }, 500); [/c] By compiling the file with the above command one can get the output as shown in the image below. setTimeout(cb, ms) - A function cb is called repeatedly at a particular intervals in ms(milliseconds) using setTimeout methods. The interval range should be included between 1-2, 147, 483 and 647 whenever the value not in a range then the interval get changed to 1 milliseconds. The snippet code below demonstrate printing a given string for every 500 milliseconds. [c]setTimeout(function(){ console.log('SPLessons stands for simple programming languages') },500);[/c] By compiling the file with the above command one can get the output as shown in the image below.

Process

shape Description

In a regular web server model, each user request is handled in the thread pool with the help of a dedicated thread whereas in Node.js process model the user requests are handled differently. The Node.js require less resources compared to other platform because the application code runs in a single thread. So, the input/output requests and a long running jobs are performed for a specific request.  In node.js a single thread is not required to wait for the request to complete and is completely free to handle the next request. The figure below demonstrate the Node.js process model architecture. With the help of few caveats process model in Node.js increase the scalability and performance. The applications with heavy work like image processing and CPU-intensive are not fit in Node.js because it take more process time and as a result the single thread is blocked. The table below gives few important properties of Node.js process model.
Property Description
process.stdin A readale stream returned by the stdin property.
process.argv The property returns an array which contain a command line argument by lunching the Node.js process.
process.stderr The property stderr returns a writable stream.
process.stdout The property stdout returns a writable stream.
process.env The property env returns the user environment object.
process.execPath The property execPath returns an absolute path name of the executable started process of Node.js.
process.exitCode The property exitCode will specify the codes for the process which exit via process.exit().
process.execArgv The property execArgv returns a set of specific command line options of Node.js by starting the process of Node.js.
process.pid The property pid returns the process PID.
process.version The property version returns the version string of Node.js.
process.versions The property versions returns the version strings and dependencies of Node.js.
process.platform The property platform returns a string which gives the os platform on which the node.js is running currently.
process.title The property title returns the current title of Node.js process.
process.arch The property arch returns a string which gives the architecture of the currently running Node.js process.
process.mainModule The property mainModule retrieve require.main in an alternate way.

shape Example

The code below demonstrate the use of properties in Node.js process model, first create a .js file with the properties as shown below. Process.js [c] process.stdout.write("SPLessons Online Tutorial" + "\n"); process.stdout.write("Process model execPath and platform Properties" + "\n"); process.argv.forEach(function(val, index, array) { console.log(index + ': ' + val); }); console.log(process.execPath); console.log(process.platform); [/c] By compiling the file with the above command one can get the output as shown in the image below.

Console

shape Description

The Node.js REPL (Read-Eval-Print-Loop) is a simple module which can be accessible for both as a standalone program or can be included in different programing applications. JavaScript code can be executed using this prompt. REPL command prompt can be accessed if a Node.js binary is initialized without passing any argument. Following are few methods of built-in console object for printing the stderr and stdout. console.info([data][, ...args]) - Multiple arguments can be given and the function is similar to the console.log. The image below gives few examples of the function console.info(). console.trace(message[, …args]) - Using the function console.trace() stack trace is printed to stderr for the current node.js position, the image below gives the example for console.trace() function. console.time(label) - The function console.time() is utilized to track the time for the process and each time must and should have different names but the time taken for a particular process can be known by using the same name with the help of the command console.timeEnd(). console.timeEnd(label) - Using the function console.timeEnd() is utilized to end the timer for the process initialized by console.time() function. The example below demonstrate the use of console.timeEnd() function. timeEnd.js [c] console.time('Process timer'); var sum = 0; for (var x=0; x<200000; x++) { sum += x; } console.log('Time taken Sum up numbers from 1 to 200000'); console.timeEnd('Process timer'); [/c] Compiling the above code will produce the output as shown in the image below. console.log([data][, …arg]) - The function console.log() is utilized to print with newline to stdout, the image below gives the example for utilizing the console.log() function. The same example can be executed by creating .js file with the code. log.js [c]console.log(“SPLessons Online Tutorials”)[/c] By compiling the code, one can get the output as shown in the image below. console.error([data][, …arg]) - The function console.error() method is similar to console.log() but the output here sent to stderr instead of stdout. This function is utilized for error messages and more use of this method can slow down the process. Multiple arguments can be passed and the first argument is used as the first message and the rest used as additional values. The snippet code below demonstrates the console.error() function. Create a .js file with the following code. err.js [c] const code = 10; console.error('error', code); console.error('error #%d', code); [/c] By compiling the code, one can get the output as shown in the image below. console.warn([data][, …arg]) - The function console.warn() is similar to console.error(), the example below demonstrates the code for warn function which print a message when a specific file opened and print a warning message if the specified file not found. [c] var fd = require("fs"); var path = "text1.txt"; fd.open(path, "r", function(err, fd){ if (err){ console.warn(err); } else{ console.log("File open successfully" + path); } }) [/c] By compiling the code, one can get the output as shown in the image below. console.assert(expression, [message]) - The function console.assert() is utilized to check the expression wither true or false, the image below demonstrates an example for console.assert() function. console.dir(obj[, options]) - The function console.dir(obj[,option]) utilize the util.inspect on obj and then prints the string to stdout.

Modules

shape Description

The modules of node.js are the packages with additional functions which can be utilized in Node.js, the modules are same like C or C++ header files. Modules in Node.js have its own context by which the modules are not polluted in global scope and also cannot interface with each other. Following are the three different types of Node.js. The Node.js Modules can be called by using its id and the core modules of node.js have small strings same as their ids, the modules can be customized in Node.js as per the requirement and the program quality can be increased.

Summary

shape Key Points

  • The Node.js global objects can be accessed from anywhere in the applications directly.
  • In Node.js a single thread is not required to wait for the request to complete and is completely free to handle the next request.
  • The Node.js REPL can be accessible for both as a standalone program or can be included in different programming applications.