2 min read
•Question 21 of 62easyHow to handle deprecation warnings in Node.js?
Managing and creating deprecation warnings.
What You'll Learn
- Understanding deprecation warnings
- Creating custom deprecations
- Handling warnings
Deprecation Warnings
$ terminalBash
# Run with no warnings
node --no-deprecation app.js
# Throw on deprecation
node --throw-deprecation app.js
# Show stack trace
node --trace-deprecation app.jsCreating Deprecations
code.jsJavaScript
const util = require('util');
// Deprecated function
const oldFunction = util.deprecate(
function oldFunction() {
return 'old result';
},
'oldFunction() is deprecated. Use newFunction() instead.',
'DEP0001'
);
oldFunction(); // Shows warning onceHandling Warnings Programmatically
code.jsJavaScript
process.on('warning', (warning) => {
console.log('Name:', warning.name);
console.log('Message:', warning.message);
console.log('Code:', warning.code);
console.log('Stack:', warning.stack);
});
// Suppress specific warnings
const originalEmit = process.emit;
process.emit = function(name, data, ...args) {
if (name === 'warning' && data.code === 'DEP0001') {
return false; // Suppress
}
return originalEmit.apply(process, [name, data, ...args]);
};Environment Variable
$ terminalBash
# Silence all deprecations
NODE_NO_WARNINGS=1 node app.js