I have a middleware function written inside my logger.js
module which I then import into app.js
and use
// ------ File : logger.js ------ //
function log(req, res, next) {
console.log('Logging details ... ');
next();
}
module.exports = log;
// ------ File : app.js -------- //
const logger = require('./logger');
app.use(logger);
The above code works without any issue and my log functionality works. However, if I export this log function in the following way (add it to the module.exports
object), I get an error
// ------ File : logger.js -------//
function log(req, res, next) {
console.log('Logging details ... ');
next();
}
module.exports.log = log;
// ------ File : app.js -------- //
const logger = require('./logger');
app.use(logger.log());
Logging details ...
D:\express-demo-worked\logger.js:4
next();
^
TypeError: next is not a function
at Object.log (D:\express-demo-worked\logger.js:4:5)
at Object.<anonymous> (D:\express-demo-worked\app.js:18:16)
at Module._compile (internal/modules/cjs/loader.js:738:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:749:10)
at Module.load (internal/modules/cjs/loader.js:630:32)
at tryModuleLoad (internal/modules/cjs/loader.js:570:12)
at Function.Module._load (internal/modules/cjs/loader.js:562:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
at internal/main/run_main_module.js:21:11
[nodemon] app crashed - waiting for file changes before starting...
Can someone explain to me why this behaves differently and how to correct the second code snippet I added here?