Middleware functions in Node.js frameworks like Express act as layers that process requests and responses in order. They can modify data, end the request, or pass control to the next middleware.
A decorator wraps a function to add new behavior before or after the original function runs, keeping the original intact.
Middleware functions take three parameters: request, response, and next. Calling next() passes control to the next middleware.
function decorator(fn) {
return function(...args) {
console.log('Before');
const result = fn(...args);
console.log('After');
return result;
};
}Passing null instead of a function causes a TypeError when trying to call fn(...args).
const express = require('express'); const app = express(); function logMiddleware(req, res, next) { console.log('Middleware start'); next(); console.log('Middleware end'); } function logDecorator(fn) { return function(req, res) { console.log('Decorator start'); fn(req, res); console.log('Decorator end'); }; } app.use(logMiddleware); app.get('/', logDecorator((req, res) => { console.log('Handler'); res.send('Hello'); }));
Middleware runs first, then the decorated handler logs 'Decorator start', then 'Handler', then 'Decorator end', then middleware logs 'Middleware end' after next() completes.
