In Node.js, util.deprecate()
wraps around a function in such a way that the function is marked deprecated. util.deprecate()
throws a warning on STDERR
, along with the supplied ERRCODE
.
util.deprecate()
is included in the util
module. The util
module can be accessed as follows:
const util = require('util');
const funcName = util.deprecate(fn,msg,code)
fn
: The deprecated function
msg
: The string that will be displayed on STDERR
code
(optional): The deprecated code. See the full list of deprecated codes here.
util.deprecate()
wraps and returns the function that is passed as the argument in such a way that it emits a warning onto the STDERR
.
When util.deprecate()
is called, it emits a DeprecationWarning
using the ‘warning’ event. If the same code
is provided for multiple calls, the warning will only be printed once.
const util = require('util')const test = util.deprecate(() => {console.log("DEPRICATED FUNC CALLED")},"test() is deprecated. Use updatedTest() instead",'ERR001')test()
Here, we wrap the test()
function using the util.deprecate()
method. When test()
is called, it emits a warning that is printed on STDERR
and the deprecated code is executed.
If either the --no-deprecation
or --no-warnings
command-line flags are utilized, or if the process.noDeprecation
property is set to true
before the first deprecation warning, the util.deprecate()
method does nothing.
If the --trace-deprecation
or --trace-warnings
command-line flags are set, or the process.traceDeprecation
property is set to true
, a warning and a stack trace are printed to STDERR
when we invoke the deprecated function for the first time.
If the --throw-deprecation
command-line flag is set, or the process.throwDeprecation
property is set to true
, then, at that point, an exception will be thrown when the deprecated function is called.
The --throw-deprecation
command-line flag and process.throwDeprecation
property outweigh --trace-deprecation
and process.traceDeprecation
.