Rawnly Rawnly - 12 days ago 5
Javascript Question

Create public variable Nodejs

Hello that's my nodejs commandline to get the weather on current position.

// Index.js
// Modules
const program = require('commander');
const clear = require('clear');
const chalk = require('chalk');
const request = require('ajax-request');
const fs = require('fs');
const json = require('read-data').json;
const jsonfile = require('jsonfile')

// Http Request to freegeoi.net
request({
url: "http://freegeoip.net/json/",
method: "GET",
data: {
format: "json"
},
}, function(err, res, body) {

// Parse the result
const data = JSON.parse(body);

// Extracting coordinates from data
let lat = data.latitude;
let long = data.longitude;
});

// forecase key
const key = "***********************";
// full forecast api url
const url = `https://api.darksky.net/forecast/${key}/${lat},${long}`;


The problem is this: i want to get variable lat and long out of the request function.

How can i do that?

Answer

You could change let lat = ... to var lat = ... because let scopes to the nearest {} block where as var scopes globally -- but this is generally bad practice.

A better option would be to call another function at the end of the request callback:

function processLatLong(lat, long) {
    //do something with lat long
}

request({
  url: "http://freegeoip.net/json/",
  method: "GET",
  data: {
     format: "json"
  },
}, function(err, res, body) {

  // Parse the result
  const data = JSON.parse(body);

  // Extracting coordinates from data
  let lat = data.latitude;
  let long = data.longitude;
  processLatLong(lat, long);
});