📜  Node.js 进程警告事件

📅  最后修改于: 2022-05-13 01:56:36.153000             🧑  作者: Mango

Node.js 进程警告事件

“警告”是进程模块中的 Process 类事件,每当 Node.js 发出进程警告时就会发出该事件。

句法:

Event: 'warning'

参数:此事件不接受任何参数作为参数。

返回值:此事件只返回一个回调函数以供进一步操作。

示例 1:

index.js
// Node.js program to demonstrate the  
// Process 'warning' Event
  
// Importing process module
const process = require('process');
  
// Intentionally emitted warning
process.emitWarning('something strange happened');
  
// Event 'warning' 
process.on('warning', (warning) => {
   console.warn("warning name - " + warning.name);
   console.warn("warning message - " + warning.message);
});


index.js
// Node.js program to demonstrate the  
// Process 'warning' Event
  
// Importing process module
const process = require('process');
  
// Intentionally emitted warning
process.emitWarning('Running out of Storage');
  
// Event 'warning' 
process.on('warning', (warning) => {
  console.warn("warning stacktrace - " + warning.stack)
});


使用以下命令运行index.js文件:

node index.js

输出:

(node:8004) Warning: something strange happened
(Use `node --trace-warnings ...` to show where
the warning was created)
warning name - Warning
warning message - something strange happened

示例 2:

index.js

// Node.js program to demonstrate the  
// Process 'warning' Event
  
// Importing process module
const process = require('process');
  
// Intentionally emitted warning
process.emitWarning('Running out of Storage');
  
// Event 'warning' 
process.on('warning', (warning) => {
  console.warn("warning stacktrace - " + warning.stack)
});

使用以下命令运行index.js文件:

node index.js

输出:

参考:https://nodejs.org/dist/latest-v16.x/docs/api/process.html#process_event_warning