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
输出:
(node:13400) Warning: Running out of Storage
(Use `node –trace-warnings …` to show where the warning was created)
warning stacktrace – Warning: Running out of Storage
at Object.
at Module._compile (node:internal/modules/cjs/loader:1109:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
at Module.load (node:internal/modules/cjs/loader:989:32)
at Function.Module._load (node:internal/modules/cjs/loader:829:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47
参考:https://nodejs.org/dist/latest-v16.x/docs/api/process.html#process_event_warning