Tinkerbell91
Tinkerbell91

Reputation: 27

calling a variable from outside a callback nodejs

im using glob from npm

gl = require("glob");
get = {};
gl("path/to/files/*.rmd", {}, function(err, files){
     get.files = files
 });
console.log(get.files)

output: undefined

what im trying to do is get access to the files from outside its callback. But, everything I try isn't working.

Upvotes: 1

Views: 788

Answers (3)

S.Mishra
S.Mishra

Reputation: 3664

Because of async nature of the callbacks, your console.log(get.files) will get called before the callback function of glob() has been called. The answers above are good. I am going to add one more answer to it.

'use strict';

const glob = require('glob');
const bluebird = require('bluebird');

const globPromise = bluebird.promisify(glob);
let get = {};
globPromise("./files/*.rmd", {})
  .then((files) => {
    console.log(files);
    get.files = files;
    console.log(get.files);
  });

Above code Promisify the whole glob NPM Package and provides you with an ability to perform asynchronous tasks. In your own code either you should write your console.log() inside the callback function or you can use Promises which will make sure that you would get called once glob does it's job.

Upvotes: 0

Edwin Babu
Edwin Babu

Reputation: 719

Use glob.sync which can be used to make a synchronous call

gl = require("glob");
let get = {};
get['files']=gl.sync("path/to/files/*.rmd", {});
console.log(get.files)

Ref: sync call glob.sync

Upvotes: 2

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

Referencing an outside variable from an inner function is perfectly acceptable, heck it's what makes JS so special. It's called closure.

But the problem is glob is asynchronous, means it will run console.log before completing the actual glob search.

So what you can do is you can console.log it inside the callback. Or make a promise out of it and console.log in the then function. Or you can maybe use async/await and await the function.

const gl = require("glob");
const get = {};
gl("./*.js", {}, function(err, files){
     get.files = files
     console.log(get);
});
// OR
const glP = function(){
    return new Promise((res, rej)=>{
        gl("./*.js", {}, function(err, files){
            if(err) rej(err);
            res(files);
       });
    })
}

glP()
.then((files)=>{
    get.files = files;
    console.log(get);
})

// OR
(async ()=>{
    const files = await glp();
    get.files = files;
    console.log(get);
})

Upvotes: 1

Related Questions