util.deprecate(fn, msg[, code])
| 版本 | 變化 | 
|---|---|
| v10.0.0 | 每個代碼隻發出一次棄用警告。  | 
| v0.8.0 | 添加於:v0.8.0  | 
參數
fn<Function> 被棄用的函數。msg<string> 調用已棄用的函數時顯示的警告消息。code<string> 棄用代碼。有關代碼列表,請參閱list of deprecated APIs。- 返回: <Function> 已棄用的函數被包裝以發出警告。
 
util.deprecate() 方法包裝 fn(可能是函數或類),使其被標記為已棄用。
const util = require('node:util');
exports.obsoleteFunction = util.deprecate(() => {
  // Do something here.
}, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.');
調用時,util.deprecate() 將返回一個函數,該函數將使用   事件發出 'warning' DeprecationWarning。第一次調用返回的函數時,將發出警告並打印到stderr。發出警告後,將調用包裝函數而不發出警告。
如果在對 util.deprecate() 的多次調用中提供了相同的可選 code ,則該 code 隻會發出一次警告。
const util = require('node:util');
const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001');
const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001');
fn1(); // Emits a deprecation warning with code DEP0001
fn2(); // Does not emit a deprecation warning because it has the same code
如果使用 --no-deprecation 或 --no-warnings 命令行 標誌,或者如果在第一個棄用警告之前將 process.noDeprecation 屬性設置為 true,則 util.deprecate() 方法不執行任何操作。
如果設置了 --trace-deprecation 或 --trace-warnings 命令行 標誌,或者 process.traceDeprecation 屬性設置為 true ,則在第一次調用已棄用的函數時將向 stderr 打印警告和堆棧跟蹤。
如果設置了 --throw-deprecation 命令行 標誌,或者將 process.throwDeprecation 屬性設置為 true ,則在調用已棄用的函數時將引發異常。
--throw-deprecation 命令行 標誌和 process.throwDeprecation 屬性優先於 --trace-deprecation 和 process.traceDeprecation 。
相關用法
- Node.js util.deprecate()用法及代碼示例
 - Node.js util.debuglog(section[, callback])用法及代碼示例
 - Node.js util.debuglog()用法及代碼示例
 - Node.js util.types.isInt16Array(value)用法及代碼示例
 - Node.js util.types.isNativeError(value)用法及代碼示例
 - Node.js util.isUndefined(object)用法及代碼示例
 - Node.js util.types.isArrayBufferView(value)用法及代碼示例
 - Node.js util.types.isMap(value)用法及代碼示例
 - Node.js util.types.isUint8ClampedArray(value)用法及代碼示例
 - Node.js util.inspect()用法及代碼示例
 - Node.js util.types.isSymbolObject(value)用法及代碼示例
 - Node.js util.isObject(object)用法及代碼示例
 - Node.js util.isString(object)用法及代碼示例
 - Node.js util.types.isPromise(value)用法及代碼示例
 - Node.js util.isPrimitive(object)用法及代碼示例
 - Node.js util.format()用法及代碼示例
 - Node.js util.isNull(object)用法及代碼示例
 - Node.js util.types.isSetIterator()用法及代碼示例
 - Node.js util.types.isArgumentsObject(value)用法及代碼示例
 - Node.js util.types.isFloat64Array()用法及代碼示例
 - Node.js util.types.isBooleanObject()用法及代碼示例
 - Node.js util.types.isInt32Array(value)用法及代碼示例
 - Node.js util.getSystemErrorName()用法及代碼示例
 - Node.js util.types.isUint16Array(value)用法及代碼示例
 - Node.js util.types.isSharedArrayBuffer()用法及代碼示例
 
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 util.deprecate(fn, msg[, code])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
