Node.js – util.deprecate() method

Node.jsServer Side ProgrammingProgramming

The util.deprecate() method wraps fn (that may be a function or class) in such a way that it is marketed as a deprecated method. The util.deprecate() method returns a function that emits a DeprecationWarning. This warning is printed to the stderr when the function is called the first time. The function is called without any warning once the warning is emitted.

Syntax

util.deprecate( fn, msg, [code] )

Parameters

The parameters are defined below:

  • fn − The function that needs to be deprecated.
  • msg − This is a warning message which is invoked once the deprecated function is called.
  • code − This is an optional parameter which displays the passed code for deprecated function.

Example 1

Create a file named "deprecate.js" and copy the following code snippet. After creating the file, use the command "node deprecate.js" to run this code.

 Live Demo

const util = require('util');
var deprecateFunction = util.deprecate(
   // Defining the deprecated function
   function () { },

   // Msg printed for deprecation
   "Warning: This method is deprecated !",

   // Deprecated API
   'Deprication API'
);
// Function call
deprecateFunction();

Output

C:\home\node>> node deprecate.js
(node:153883) [Deprication API] DeprecationWarning: Warning: This method is deprecated !

Example 2

 Live Demo

const util = require('util');

function fun() {
   console.log("Welcome to Tutorials Point");
}

var msg = 'This function is deprecated'
var code = 'DEP0001';
var deprecateFunction = util.deprecate(fun, msg, code);

// Function call
deprecateFunction();

Output

C:\home\node>> node deprecate.js
Welcome to Tutorials Point
(node:157003) [DEP0001] DeprecationWarning: This function is deprecated
raja
Published on 17-Aug-2021 11:14:33
Advertisements