warning{Error} 警告的主要属性有:name{string} 警告的名称。默认值:'Warning'。message{string} 系统提供的对此警告的描述。stack{string} 当警告触发时,包含代码位置的堆栈信息。
任何时候 Node.js 触发进程警告,都会触发 'warning' 事件。
进程警告与进程错误的相似之处,在于两者都描述了需要引起用户注意的异常条件。 区别在于,警告不是 Node.js 和 Javascript 错误处理流程的正式组成部分。 一旦探测到可能导致应用性能问题,缺陷或安全隐患相关的代码实践,Node.js 就可发出警告。
process.on('warning', (warning) => {console.warn(warning.name); // 打印警告名称console.warn(warning.message); // 打印警告信息console.warn(warning.stack); // 打印堆栈信息});
默认Node.js会打印进程警告到stderr。使用--no-warnings的命令行选项可以阻止默认从console输出信息,
但是'warning'事件仍然会被process对象发出。
下面的例子展示了当一个事件绑定了太多的监听器时,输出到stderr的警告。
$ node> events.defaultMaxListeners = 1;> process.on('foo', () => {});> process.on('foo', () => {});> (node:38638) MaxListenersExceededWarning: Possible EventEmitter memory leakdetected. 2 foo listeners added. Use emitter.setMaxListeners() to increase limit
与上述相反,如下例子关闭了默认的警告输出,并且给'warning'事件添加了一个定制的处理器。
$ node --no-warnings> const p = process.on('warning', (warning) => console.warn('Do not do that!'));> events.defaultMaxListeners = 1;> process.on('foo', () => {});> process.on('foo', () => {});> Do not do that!
--trace-warnings命令行选项可以让默认的控制台输出警告信息时,包含警告的全部堆栈信息。
使用--throw-deprecation命令行选项标志启动Node.js,会使得自定义的弃用警告作为异常信息抛出来。
使用--trace-deprecation命令行选项标志,会使得自定义的弃用警告打印到stderr,包括其堆栈信息。
使用--no-deprecation命令行选项标志,会阻止报告所有的自定义的弃用警告。
*-deprecation 命令行选项标志,只会影响使用名字为 'DeprecationWarning' 的警告。
