process.emitWarning(warning[, options])


  • warning <string> | <Error> 发出的警告。
  • options <Object>

    • type <string> 如果 warning 是String, type 是警告类型的名字。 默认值: Warning
    • code <string> 当前警告的唯一标识符。
    • ctor <Function> 如果warning是String,ctor是可选的function,用于限制生成的堆栈信息。默认process.emitWarning
    • detail <string> error的附加信息。

process.emitWarning()方法可用于发出定制的或应用特定的进程警告。 可以通过给process.on('warning')事件增加处理器,监听这些警告。

// Emit a warning with a code and additional detail.
process.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

在上面例子中,process.emitWarning()内部生成了一个Error对象,并传递给process.on('warning')事件。

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参数项都会被忽略。

  • warning <string> | <Error> The warning to emit.
  • options <Object>

    • type <string> When warning is a String, type is the name to use for the type of warning being emitted. Default: 'Warning'.
    • code <string> A unique identifier for the warning instance being emitted.
    • ctor <Function> When warning is a String, ctor is an optional function used to limit the generated stack trace. Default: process.emitWarning.
    • detail <string> Additional text to include with the error.

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.

// Emit a warning with a code and additional detail.
process.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

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

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'
});

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