These objects are global in nature and are available in all modules. There is no need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings, object etc.

Topics Covered :

  • Console
  • Process
  • Scheduling Timers
    • setImmediate(callback[, …args])
    • setInterval(callback, delay[, …args])
    • setTimeout(callback, delay[, …args])
  • Cancelling Timers
    • clearImmediate(immediateObject)
    • clearInterval(intervalObject)
    • clearTimeout(timeoutObject)
  • Dirname : __dirname
  • Filename : __filename
  • Exports
  • Module
  • Require

Console

The console provides a simple debugging console. Used to print information on stdout and stderr. It uses built-in methods for printing informational, warning and error messages. It exports two specific components :

Console class : The class have methods like console.log(), console.error() and console.warn().
Global console instance: The instance is configured to write to process.stdout and process.stderr. The global console can be used without calling require(‘console’).

Example :

Create a file name text.js . Write the following code in text.js :

console.log('hello world');
// Prints hello world, to stdout 
console.log('hello %s', 'world'); 
// Prints hello world, to stdout 
console.error(new Error('Error')); 
// Prints Error: 'Error', to stderr 
const name = 'Global Objects'; 
console.warn(`Danger ${name}! Danger!`); 
// Prints: Danger Global Objects! Danger!, to stderr

Run Command :

C:\Users\Your Name>node text.js

Result :

hello world
hello world
Error: Error
Danger Global Objects! Danger!

There are two ways of using a console synchronous and asynchronous. When the destination is a file or a terminal synchronous console is used. When the destination is a pipe asynchronous console is used.

 S.no.MethodDescription
   1.console.assert(value[, message][,args …])If the value is true, the error message is formatted using util.format() and used as the error message.
   2.newConsole(stdout[, stderr])Creates a new Console.
   3.console.clear()Checks whether stdout is a TTY if true will attempt to clear the TTY.
   4.console.count([label])An internal counter has been called with the given label.
   5.console.countReset([label=’default’])Resets the internal counter given to label.
   6.console.debug(data[, …args])Alias for console.log().
   7.console.dir(obj[, options])Uses util.inspect() on obj options alter certain aspects of the formatted string.
   8.console.dirxml(…data)This method does not produce any XML formatting, it passes arguments to console.log().
   9.console.error([data][, …args])Prints to stderr, the arguments are all passed to util.format().
  10.console.group([…label])Increases indentation of subsequent lines.
  11.console.groupCollapsed()Alias for console.group().
  12.console.groupEnd()Decreases indentation of subsequent lines.
  13.console.info([data][, …args])Alias for console.log().
  14.console.log([data][, …args])Prints to stdout with newline.
  15.console.time(label)Starts a timer.
  16.console.timeEnd(label)Stops a timer that was previously started by calling console.time(). Prints the result to stdout.
  17.console.trace([message][, …args])Prints to stderr the string. the util.format() formatted message and stack trace to the current position in the code.
 18.console.warn([data][, …args])Alias for console.error().

Inspector only methods

These methods does not display anything unless used in the inspector.

S.no.MethodDescription
1.console.profile([label])Starts a JavaScript CPU profile with an optional label until console.profileEnd() is called.
2.console.profileEnd()Stops the current JavaScript CPU profiling session.
3.console.table(array[, columns])Prints to stdout the array formatted as a table.

Process

  • Used to get information over the current process.
  • Provides multiple events related to process activities.

Process Events

It is an instance of EventEmitter. It emits the following events :

S.No.EventDescription
1.exitEmitted when the Node.js process is about to exit as a result of either by the process.exit Code property, or the exitCode argument.
2.beforeExitEmitted when Node.js empties its event loop and has no additional work to schedule and can make asynchronous calls.
3.disconnectEvent will be emitted when the IPC channel is closed.
4.messageEmitted whenever a message sent by a parent process using childprocess.send() is received by the child process.
5.uncaughtExceptionEmitted whenever a Promise has been rejected and an error handler was attached to it later than one turn of the event loop.
6.Signal EventsEmitted when the Node.js process receives a signal.
7.warningEmitted whenever Node.js emits a process warning.
8.rejectionHandledEmitted whenever a Promise has been rejected and an error handler was attached to it later than one turn of the event loop.
9.unhandledRejectionEmitted whenever a Promise is rejected and no error handler is attached to the promise within a turn of the event loop.

Example :

Create a file name text.js . Write the following code in text.js :

process.on('exit', function(code) {
 // The code below will never execute.
 setTimeout(function() {
    console.log("This will not run");
 }, 0);
 console.log('About to exit with code:', code);
});
console.log("Program Ended");

Run Command :

C:\Users\Your Name>node text.js

Result :

Program Ended
About to exit with code: 0

Process Properties

To better control system interactions, process properties are used :

S.No.PropertyDescription
1.stdinWritable Stream to stdin
2.stdoutWritable Stream to stdout.
3.stderrWritable Stream to stderr
4.argvreturns an array containing the command line arguments passed (Arguments node and javascript file)
5.argv0stores a read-only copy of the original value of argv[0]
6.envreturns an object containing the user environment
7.execPathreturns the absolute pathname of the executable that started the Node.js process.
8.execArgvreturns the set of Node.js-specific command-line options passed
9.exitCodeSpecifying a code to process.exit(code) will override any previous setting
10.configreturns an Object containing the JavaScript
11.pidreturns the PID of the process.
12.archreturns a String identifying the processor architecture that the Node.js process is currently running on.

Methods

S.No.MethodDescription
1.abort()Emit a abort. It causes the node to exit and generate a core file.
2.cwd()Returns the current working directory of the Node.js process.
3.exit([code])Method instructs Node.js to terminate the process synchronously.
4.chdir(directory)Changes the current working directory of the Node.js process or throws an exception if doing so fails.
5.getegid()Returns the numerical effective group identity of the Node.js process.
6.setegid(id)Sets the effective group identity of the process.
7.geteuid()Returns the numerical effective user identity of the process.
8.getgid()Returns the numerical group identity of the process.
9.getuid()Returns the numeric user identity of the process.
10.seteuid(id)Sets the effective user identity of the process.
11.getgroups()Returns an array with the supplementary group.
12.setgid()sets the group identity of the process.
13.setuid()sets the user identity of the process.

Scheduling Timers

In Node.js a timer is a global function and an internal construct that calls a given function after a certain period of time. When a timer’s function is called it varies depending on which method was used to create the timer and what other work the Node.js event loop is doing.

setImmediate(callback[, …args])

callback     :     It is a callback function to call at the end of this turn of Event Loop

..args          :     Optional arguments to pass when the callback is called                                                                                                                 

  • It sets the ‘immediate’ execution of the callback after I/O events callback returns an Immediate for clearImmediate().
  • When there are multiple calls for setImmediate(), then the callback functions are queued for execution in the order in which they are created.
  • For every event loop iteration, entire callback queue is processed.
  • When an immediate timer is queued from inside an executing callback, then that timer will not be triggered until the next event loop iteration.

Example :

Create a file name text.js . Write the following code in text.js :

setImmediate(function () {
 console.log('immediate');
});

Run Command :

C:\Users\Your Name>node text.js

The output is printed after a little delay.

 The method has a custom variant for promises i.e. util.promisify() : 

Example :

Create a file name text.js . Write the following code in text.js :

const util = require('util');
const setImmediatePromise= util.promisify(setImmediate);

setImmediatePromise('aaa').then((value) => {
  // value === 'aaa' (passing values is optional)
  // This is executed after all I/O callbacks.
});

// or with async function
async function timerExample() {
  console.log('Before I/O callbacks');
  await setImmediatePromise();
  console.log('After I/O callbacks');
}
timerExample();

Run Command :

C:\Users\Your Name>node text.js

Result :

Before I/O callbacks
After I/O callbacks

Note : Callback has to be a function otherwise TypeError will be thrown.

setInterval(callback, delay[, …args])

callback     :     It is a callback function to call when the timer pass.

delay          :     It is of type number. The number of milliseconds to wait before calling the callback.

..args          :     Optional arguments to pass when the callback is called.   

Run callback repeatedly after at least delay of milliseconds. OS timer granularity and system load may affect actual delay. Returns a Timeout for use with clearInterval(). A timer cannot span larger than 2147483647 or less than 1, otherwise, the delay will be set to 1.

Example :

Create a file name text.js . Write the following code in text.js :

function printHello(){
   console.log( "Hello, World!");
}
// Call the above function after 2 seconds
setInterval(printHello, 2000);

Run Command :

C:\Users\Your Name>node text.js

The output is printed after delay.

setTimeout(callback, delay[, …args])

callback     :     It is a callback function to call when the timer pass.

delay          :     It is of type number. The number of milliseconds to wait before calling the callback.

…args         :     Optional arguments to pass when the callback is called.

Executes a one-time callback after the delay of milliseconds. Returns a Timeout for clearTimeout(). A timer cannot span larger than 2147483647 or less than 1, otherwise, the delay will be set to 1.

Example :

Create a file name text.js . Write the following code in text.js :

function printHello(){
   console.log( "Hello, World!");
}
//Call above function after 2 seconds
setTimeout(printHello, 2000);

Run Command :

C:\Users\Your Name>node text.js

The output is printed after a little delay.

 The method has a custom variant for promises i.e. util.promisify() : 

Example :

Create a file name text.js . Write the following code in text.js :

const util = require('util');
const setTimeoutPromise = util.promisify(setTimeout);

setTimeoutPromise(40, 'foobar').then((value) => {
  // value === 'foobar' (passing values is optional)
  // This is executed after about 40 milliseconds.
console.log(value);
});

Run Command :

C:\Users\Your Name>node text.js

The output is printed after delay.

Note: Callback has to be a function otherwise TypeError will be thrown.

Cancelling Timers

The setImmediate(), setInterval() and setTimeout() methods return objects that represent the scheduled timers. Cancelling timers can be used to cancel the timer and stop triggering.

clearImmediate(immediateObject)

The clearTimeout(t) global function is used to stop a timer returned by the setImmediate() function.

Example :

Create a file name text.js . Write the following code in text.js :

function printHello(){
   console.log( "Hello, World!");
}

// Call above function after 2 seconds
var t = setImmediate(printHello, 2000);

// Clear the timer
clearTimeout(t);

Run Command :

C:\Users\Your Name>node text.js

You will not find anything printed in the output.

clearInterval(intervalObject)

The clearTimeout(t) global function is used to stop a timer returned by the setInterval() function.

Example :

Create a file name text.js . Write the following code in text.js :

function printHello(){
   console.log( "Hello, World!");
}

// Call above function after 2 seconds
var t = setInterval(printHello, 2000);

// Clear the timer
clearTimeout(t);

Run Command :

C:\Users\Your Name>node text.js

You will not find anything printed in the output.

clearTimeout(timeoutObject)

The clearTimeout(t) global function is used to stop a timer returned by the setTimeout() function.

Example :

Create a file name text.js . Write the following code in text.js :

function printHello(){
   console.log( "Hello, World!");
}

// Call above function after 2 seconds
var t = setTimeout(printHello, 2000);

// Clear the timer
clearTimeout(t);

Run Command :

C:\Users\Your Name>node text.js

You will not find anything printed in the output.

The following variables exist only in the scope of modules, they may appear to be global but are not :

  • __dirname
  • __filename
  • exports
  • module
  • require()

__dirname

The __dirname is same as the path.dirname() of the __filename. It is of type string. It specifies the directory name of the current module.

Example :

Create a file name test.js . Write the following code in test.js :

// Prints the value of __dirname
console.log( __dirname );

Run Command :

C:\Users\Your Name>node dirname.js

__filename

The __filename is the resolved absolute path of the current module. The value within a module is the path to that module file. It is of type string. It specifies the filename of the code being executed.

Example :

Create a file name test.js . Write the following code in test.js :

//Print the value of __filename
console.log( __filename );

Run Command :

C:\Users\Your Name>test.js

 Exports

exports is a shortcut reference to the module.exports . It’s a variable available within the file-level scope of the module and assigned the value of module.exports before the module are appraised.

It allows a shortcut to the module.exports, so that module.exports.f = … can be written as exports.f = … . However, if a new value is assigned to exports it is no longer bound to the module.exports :

// Exported from require of module
module.exports.hello = true; 
// Not exported, only available in the module
exports = { hello: false };

Module

The fundamental node building block is called a module which maps directly to a file. A module is of type object. The module free variable is a reference to the object representing the current module. a module is not actually a global but rather local to each module. The module Object free variable is a reference to the object representing the current module.

Built-in modules which you can use without any further installation :

ModuleDescription
fsTo handle the file system.
assertProvides a set of assertion tests.
bufferTo handle binary data.
child_processTo run a child process.
clusterTo split a single Node process into multiple processes.
cryptoTo handle OpenSSL cryptographic functions.
dgramProvides implementation of UDP datagram sockets.
dnsTo do DNS lookups and name resolution functions.
eventsTo handle file paths.
pathTo handle the file system.
httpTo make Node.js act as an HTTP server.
httpsTo make Node.js act as an HTTPS server.
netTo create servers and clients.
osProvides information about the operation system.
querystringTo handle URL query strings.
readlineTo handle readable streams one line at the time.
streamTo handle streaming data.
string_decoderTo decode buffer objects into strings.
timersTo execute a function after a given number of milliseconds.
tlsTo implement TLS and SSL protocols.
ttyProvides classes used by a text terminal.
urlTo parse URL strings.
utilTo access utility functions.
vmTo compile JavaScript code in a virtual machine.
zlibTo compress or decompress files.

Require()

Require is used to load a module and its return value is typically assigned to a variable. It reads a javascript file, executes the file and then proceeds to return the exports object.

Syntax :

require(‘module_name’)

require.cache

Modules are cached in this object when they are required.

require.resolve(request[, options])

request: It is of type string. Contains the path of the module to resolve.

options: It is of type object. Contains path to resolve module location from.

require.resolve.paths(request)

request: It is of type string. Contains the module path whose lookup paths are being retrieved.

Learn More-