Open In App

Node.js util.inherits() Method

The “util” module provides ‘utility’ functions that are used for debugging purposes. For accessing those functions we need to call them (by ‘require(‘util’)‘).

The util.inherits() (Added in v0.3.0) method is an inbuilt application programming interface of the util module in which the constructor inherits the prototype methods from one to another and the prototype of that constructor is set to a new object which is created from superConstructor. It is mostly used for adding or inheriting some input validation on top of Object.setPrototypeOf(constructor.prototype, superConstructor.prototype). And superConstructor can be accessed through the constructor.super_property for additional convenience. Its (i.e, util.inherits()) usage is not much encouraged instead use of ES6 class and extends keywords is recommended in order to get language level inheritance support.



Syntax:

const util = require('util');
util.inherits(constructor, superConstructor)

Parameters: This function accepts two parameters as mentioned above and described below:



node index.js

Output:

1.> Returning util.inherits(): undefined

2.> [Function: streamData]

3.> <ref *1> [Function: EventEmitter] {once: [Function: once], ….., listenerCount: [Function (anonymous)]}

4.> Instance of EventEmitter true

5.> ‘===’ comparison of an Instance with EventEmitter true

6.> Data Stream Received: “Finally it started!”

Example 2: Filename: index.js




// Node.js program to demonstrate the 
// util.inherits() method in ES6
  
// Using require to access util module 
const util = require('util');
const { inspect } = require('util');
const emitEvent = require('events');
  
class streamData extends emitEvent {
  write(stream_data) {
  
      // Emitting the data stream
    this.emit('stream_data', stream_data);
  }
}
  
const manageStream = new streamData('default');
console.log("1.>", inspect(manageStream, false, 0, true))
console.log("2.>", streamData)
  
// Returns true
console.log("3.>", streamData === manageStream) 
console.log("4.>", manageStream)
manageStream.on('stream_data', (stream_data) => {
  // Prints the write statement after streaming
  console.log("5.>", `Data Stream Received: "${stream_data}"`);
});
  
// Write on console
manageStream.write('Finally it started streaming with ES6');

Run index.js file using the following command:

node index.js

Output:

1.> streamData { _events: [Object: null prototype] {}, ……………………, [Symbol(kCapture)]: false}

2.> [Function: streamData]

3.> false

4.> streamData {_events: [Object: null prototype] {}, ……………………, [Symbol(kCapture)]: false}

5.> Data Stream Received: “Finally it started streaming with ES6”

Reference: https://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor


Article Tags :