I want to write my own function for example:
own_function.js:
module.exports = function(req, res, next){
var js_object;
// Do some stuff with above javascript object
// After I want to attach "js_object" to request object:
req.js = js_object;
next();
// also tried next(req, res);
}
I want to use this function in a different for example "main.js" file:
main.js:
var own_function = require(__dirname + '/own_function');
own_function(req, res, function(){
// Also tried own_function(req, res, function(req, res){
console.log(req.js_object);
});
It's not working I got undefined object. I think it's only syntax issue, but I don't know what is the correct syntax, please help me. Thank you.
In main.js
you're calling console.log(req.js_object);
, but in own_function.js
, you're setting req.js
, not req.js_object
. Those two things need to match. I'd suggest changing main.js
:
var own_function = require(__dirname + '/own_function');
own_function(req, res, function(){
console.log(req.js); // was req.js_object
});