0

Node.js code to extract all the links from the web page and store it in the variable that stores the data inside the scope of the function but not showing the data outside the scope of the function.

var ineed = require('ineed');
var url = require('get-urls');
var list = require('collections/list');
var fs = require('fs');
var arr = [];

ineed.collect.hyperlinks.from("https://energy.economictimes.indiatimes.com/rss/", function (err, response, result) {
    var links = url(JSON.stringify(result)).toArray();
    var str="/rss/";
    for(var i = 0; i<links.length; i++){
      if((links[i].search(str))>-1){
        arr.push(links[i]);
      }
    }
    console.log(arr);
    // I am getting the output of the array here
  })

  //While printing the array I am not getting the output
  console.log(arr);
coder
  • 8,346
  • 16
  • 39
  • 53
Ghost
  • 1
  • 1

1 Answers1

1

You got noting in second console.log just because your code wich collect information run asynchronously and arr accepted any value after the first console.log executed. So either you rewrite your code on "clean" promises like

new Promise((resolve)=>ineed.collect.hyperlinks.from(
     "https://energy.economictimes.indiatimes.com/rss/", 
     function (err, response, result) {
         var links = url(JSON.stringify(result)).toArray();
         var str="/rss/";
         for(var i = 0; i<links.length; i++){
           if((links[i].search(str))>-1){
             arr.push(links[i]);
           }
         }
         resolve(arr)
     }
  ))
  .then((arr)=>console.log(arr));

or convert to async/await function.

Vasyl Moskalov
  • 4,242
  • 3
  • 20
  • 28
  • I want to accesst the arr array globaly in my program for further processing but I am not getting value globally. – Ghost Jun 25 '18 at 08:12
  • Actually by this code I want to make an array of urls which I want to use in another modules, but anyhow I am not getting these urls globally I tried to store it another array but it stores the element but not getting getting any value outside the function. – Ghost Jun 25 '18 at 08:22