Reputation: 11
I have a variable var sessions={} in file called 'UserSessions.js'. I am maintaining some information of each user in sessions={} with a unique timestamp. I have exported this variable to make it available to other files.
When I access the sessions={} in main file 'app.js' everything works fine.
But when I try to access same variable from another file 'Sessiongreet.js', it gives error.
Here is how I access the data :
Suppose '2017-04-07T11:55:40.162Z' is the unique timestamp assigned only once.
In app.js:
This Works fine:
const UserSessions=require('./UserSessions.js');
sessionId='2017-04-07T11:55:40.162Z';
var data=UserSessions.sessions[sessionId].context;
In sessionGreet.js:
This gives error:
const UserSessions=require('./UserSessions.js');
sessionId='2017-04-07T11:55:40.162Z';
var data=UserSessions.sessions[sessionId].context;
I know that UserSessions.sessions[sessionId].context exists as it is accessible in app.js file before accessing it in another file.
Here is the exact error what I get :
TypeError: Cannot read property '2017-04-07T11:55:40.162Z' of undefined
at initSession (/media/row_hammer/sessionGreet.js:24:33)
at Object.run (/media/row_hammer/sessionGreet.js:67:2)
at Object.handlePostback (/media/row_hammer/sessionTemp.js:89:19)
at runPostback (/media/row_hammer/app.js:113:15)
at /media/row_hammer/app.js:161:3
at Object.findOrCreateSession (/media/row_hammer/UserSessions.js:83:4)
at Bot.bot.on (/media/row_hammer/app.js:159:15)
at emitThree (events.js:116:13)
at Bot.emit (events.js:194:7)
at Bot._handleEvent (/media/row_hammer/node_modules/messenger-bot/index.js:254:10)
Also, In sessionGreet.js:
//EVEN this line shows 'undefined'
console.log(UserSessions.sessions);
Why am I getting this error even though flow of program is correct?
Upvotes: 1
Views: 53
Reputation: 2426
It may be that app.js and Sessiongreet.js are in different folders.
'./UserSessions.js' means that UserSessions.js is in the same folder as the file issuing the require().
If app.js is in the same folder as UserSessions.js, but Sessiongreet.js is in different folder, this would explain your issue.
Upvotes: 1