避免重复告警


作为最佳实践,警告应该在每个进程中最多发出一次。 为了达到上述的要求,推荐在使用emitWarning()之前用一个简单的布尔值做判断,如下例所示:

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

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