1

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?

1
  • can you post here a code from UserSessions.js ? It interesting how do you export the "session" variable. Commented Apr 7, 2017 at 13:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

no.. 'UserSessions.js' and 'app.js' are in same folder.
btw..I found out the solution... I use global.sessions={} instead of var sessions={}. Simply made 'sessions={}' global.Its working well now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.