On running the following code, the console says logger.log is not a function even though I am exporting the function from index.js.
index.js
const winston = require('winston');
const error = require('./middleware/error');
const logger=winston.createLogger({transports:[new winston.transports.Console(),
new winston.transports.File({filename:'logfile.log'})
]});
app.use(error);
module.exports = logger;
error.js
const winston = require('winston');
const logger = require('../index');
module.exports = function(err,req,res,next){
//Log the exception
logger.log('error',err.message);
res.status(500).send('Something failed.');
}
This is what the terminal says:
TypeError: logger.log is not a function
at module.exports (C:\Users\hp\Desktop\YouStart\nodejs-mosh\vidly\5.13- Project- Restructure the App\vidly\middleware\error.js:8:12)
at C:\Users\hp\Desktop\YouStart\nodejs-mosh\vidly\5.13- Project- Restructure the App\vidly\node_modules\express-async-errors\index.js:5:20
at Layer.handle_error (C:\Users\hp\Desktop\YouStart\nodejs-mosh\vidly\5.13- Project- Restructure the App\vidly\node_modules\express\lib\router\layer.js:71
Circular dependencies are never a good pattern. You're forcing error.js
to resolve its exports before index.js
can resolve its exports - this is probably leading to your issue.
You should avoid circular dependencies basically in every situation. It's easy: You never need to have error.js
require index.js
, because you can instead just export a function that lets you pass whatever is needed from index.js
as a parameter. It would look like this:
index.js
const winston = require('winston');
const logger = winston.createLogger({transports:[new winston.transports.Console(),
new winston.transports.File({filename:'logfile.log'})
]});
const error = require('./middleware/error')(logger); //pass logger to error middleware
app.use(error);
error.js
module.exports = function(logger) {
//return function configured with logger to use as middleware
return function(err,req,res,next) {
//Log the exception
logger.log('error',err.message);
res.status(500).send('Something failed.');
}
};