Node.js – util.deprecate() 方法
该方法包装fn(可能是一个函数或类),使其作为不推荐使用的方法进行销售。该方法返回一个发出DeprecationWarning的函数。第一次调用该函数时,此警告会打印到stderr。一旦发出警告,就会在没有任何警告的情况下调用该函数。util.deprecate()util.deprecate()
语法
util.deprecate( fn, msg, [code] )
参数
参数定义如下:
fn-需要弃用的功能。
msg- 这是一个警告消息,一旦调用不推荐使用的函数就会调用。
code- 这是一个可选参数,显示不推荐使用的函数的传递代码。
示例1
创建一个名为“deprecate.js”的文件并复制以下代码片段。创建文件后,使用命令“nodedeprecate.js”运行此代码。
const util = require('util');
var deprecateFunction = util.deprecate(
//定义已弃用的函数
function () { },
//为弃用而打印的消息
"Warning: This method is deprecated !",
//已弃用的API
'Deprication API'
);
//函数调用
deprecateFunction();输出结果C:\home\node>> node deprecate.js (node:153883) [Deprication API] DeprecationWarning: Warning: This method is deprecated !
示例2
const util = require('util');
function fun() {
console.log("Welcome to nhooo.com");
}
var msg = 'This function is deprecated'
var code = 'DEP0001';
var deprecateFunction = util.deprecate(fun, msg, code);
//函数调用
deprecateFunction();输出结果C:\home\node>> node deprecate.js Welcome to nhooo.com (node:157003) [DEP0001] DeprecationWarning: This function is deprecated