process.emitWarning(warning[, options])


  • warning <string> | <Error> 要发出的警告。
  • options <Object>
    • type <string>warning 是一个 String 时,type 是用于发出警告的 类型 的名称。默认值: 'Warning'
    • code <string> 正在发出的警告实例的唯一标识符。
    • ctor <Function>warning 是一个 String 时,ctor 是一个可选函数,用于限制生成的堆栈跟踪。默认值: process.emitWarning
    • detail <string> 要随错误一起包含的附加文本。

process.emitWarning() 方法可用于发出自定义或特定于应用的进程警告。可以通过向 'warning' 事件添加处理程序来监听这些警告。

【The process.emitWarning() method can be used to emit custom or application specific process warnings. These can be listened for by adding a handler to the 'warning' event.】

import { emitWarning } from 'node:process';

// Emit a warning with a code and additional detail.
emitWarning('Something happened!', {
  code: 'MY_WARNING',
  detail: 'This is some additional information',
});
// Emits:
// (node:56338) [MY_WARNING] Warning: Something happened!
// This is some additional informationconst { emitWarning } = require('node:process');

// Emit a warning with a code and additional detail.
emitWarning('Something happened!', {
  code: 'MY_WARNING',
  detail: 'This is some additional information',
});
// Emits:
// (node:56338) [MY_WARNING] Warning: Something happened!
// This is some additional information

在此示例中,一个 Error 对象由 process.emitWarning() 内部生成,并传递给 'warning' 处理程序。

【In this example, an Error object is generated internally by process.emitWarning() and passed through to the 'warning' handler.】

import process from 'node:process';

process.on('warning', (warning) => {
  console.warn(warning.name);    // 'Warning'
  console.warn(warning.message); // 'Something happened!'
  console.warn(warning.code);    // 'MY_WARNING'
  console.warn(warning.stack);   // Stack trace
  console.warn(warning.detail);  // 'This is some additional information'
});const process = require('node:process');

process.on('warning', (warning) => {
  console.warn(warning.name);    // 'Warning'
  console.warn(warning.message); // 'Something happened!'
  console.warn(warning.code);    // 'MY_WARNING'
  console.warn(warning.stack);   // Stack trace
  console.warn(warning.detail);  // 'This is some additional information'
});

如果将 warning 作为 Error 对象传递,则会忽略 options 参数。

【If warning is passed as an Error object, the options argument is ignored.】