避免重复警告


作为最佳实践,每个进程只应触发一次警告。 为此,建议将 emitWarning() 放在一个简单的布尔标志后面,如下例所示:

function emitMyWarning() {
  if (!emitMyWarning.warned) {
    emitMyWarning.warned = true;
    process.emitWarning('Only warn once!');
  }
}
emitMyWarning();
// 触发: (node: 56339) Warning: Only warn once!
emitMyWarning();
// 什么都不触发

As a best practice, warnings should be emitted only once per process. To do so, it is recommended to place the emitWarning() behind a simple boolean flag as illustrated in the example below:

function emitMyWarning() {
  if (!emitMyWarning.warned) {
    emitMyWarning.warned = true;
    process.emitWarning('Only warn once!');
  }
}
emitMyWarning();
// Emits: (node: 56339) Warning: Only warn once!
emitMyWarning();
// Emits nothing