1

I'm working on NodeJS for event capturing purpose. All the calls will be coming to getme function. From this function I'm calling getUserLocation() function which return Geolocation based on ip. How can I updated Global variable based on this values?

var getClientAddress = function (req) {
return (req.get('x-forwarded-for') || '').split(',')[0]  || req.connection.remoteAddress;
}

var getClientLocation = function (ipaddress, callback) {
    freegeoip.getLocation(ipaddress, function(err, location) {
        if (err) throw err;
        return callback(location);
    });
}

var store = [{'hello': 'world', 'country': 'India', 'City': 'Indupur'}];

for (eve=0;eve<store.length;eve++){
if(!store[eve].lat){
        clientIp = getClientAddress(req);
        getClientLocation("XXX:XX:XX:XXX", function(resp) {
            console.log(resp);
            store[eve].country = store[eve].country || resp.country_name;
            store[eve].region = store[eve].region || resp.region_name;
            store[eve].city = store[eve].city || resp.city;
            store[eve].lat = store[eve].lat || resp.latitude;
            store[eve].lng =  store[eve].lng || resp.longitude;
        });

    }

But store is not accessible. It is undefined. How can I update store?

Actual Code: Here is the actual code :

https://github.com/Gowtham95india/CapVengine/blob/master/server.js

Here is the error message:

Server started! At http://localhost:8080
Redis started! Ready to perform
{ e: '[{"device_id":"dsfkdjf-dsfdls-fejfskj-e2oiej2j3jf","user_id":2124,"email":"gowtham95india@gmail.com","event_properties":{"utm_source":"HelloWorld"}, "lat":""}]',
  v: 2 }
2017-02-11T09:02:10.838Z


{ ip: '121.244.122.142',
  country_code: 'IN',
  country_name: 'India',
  region_code: 'MH',
  region_name: 'Maharashtra',
  city: 'Phursungi',
  zip_code: '412308',
  time_zone: 'Asia/Kolkata',
  latitude: 18.4667,
  longitude: 73.9833,
  metro_code: 0 }
/Users/GowthamSai/Documents/repo/capeve/server.js:111
                store[eve].country = store[eve].country || resp.country_name;
                                               ^

TypeError: Cannot read property 'country' of undefined
    at /Users/GowthamSai/Documents/repo/capeve/server.js:111:48
    at /Users/GowthamSai/Documents/repo/capeve/server.js:36:16
    at Request._callback (/Users/GowthamSai/Documents/repo/capeve/node_modules/node-freegeoip/lib/freegeoip.js:25:16)
    at Request.self.callback (/Users/GowthamSai/Documents/repo/capeve/node_modules/request/request.js:187:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:191:7)
    at Request.<anonymous> (/Users/GowthamSai/Documents/repo/capeve/node_modules/request/request.js:1048:10)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at IncomingMessage.<anonymous> (/Users/GowthamSai/Documents/repo/capeve/node_modules/request/request.js:969:12)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)
gwthm.in
  • 638
  • 9
  • 24
  • Generally to define a global variable in javascript, the keyword `var` is not to be used during function declaration. Try omitting the keyword `var` during the declaration of the store variable. – Siddharth Srinivasan Feb 11 '17 at 08:38
  • Which error exactly do you see? – oklas Feb 11 '17 at 08:39
  • @SiddharthSrinivasan - That is horrible advice. All variables in Javascript should be explicitly declared. You should just declare them in the desired scope. Implicit or accidental globals are a horrible idea and, in fact, becomes errors when running in strict mode (the safe way to program). – jfriend00 Feb 11 '17 at 08:40
  • Add ';' after declarations of `getClientAddress` and `getClientLocation` and before `store` declaration. – oklas Feb 11 '17 at 08:41
  • `store` should be accessible just fine. Why do you think it is `undefined`? – jfriend00 Feb 11 '17 at 08:44
  • That is reason why I ask error message exaclty. Seems `store[eve]` or `store.length` may not work without console error if store `undefined`. So assumption about store is undefined is doubtfully. – oklas Feb 11 '17 at 08:58
  • I'm updating the question. – gwthm.in Feb 11 '17 at 09:02

1 Answers1

1

Your problem is not with accessing store. That global variable is defined.

Your problem is accessing store[eve] because you never define that.

You go direct to trying to read store[eve].lat without ever assigning anything to store[eve] (e.g. with store[eve] = store[eve] || {}).


You also have a couple of other problems, which are the root cause of that issue, which are explained by:

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • if I'm not wrong, inside for loop eve holds the value of indexed position. So, store[eve] will be the first element of store for first iterations. Correct me if I'm wrong. – gwthm.in Feb 11 '17 at 09:06
  • @7H3IN5ID3R — You're wrong. See the two links at the end of the answer. `eve` will be updated before the callback fires. – Quentin Feb 11 '17 at 09:12
  • yes, you are right. eve value became 1. store[1] which is obviously undefined. Thanks for pointing the mistake. In this case, which will be the good way to correct this? – gwthm.in Feb 11 '17 at 09:34
  • I solved this using forEach. one more doubt, I'm not able to access redis_result inside getRedisResult callback. I'm assigning it but sill empty outside of that. – gwthm.in Feb 11 '17 at 10:30