0

I'm trying to return arr when final() is called....

  function final(){
        var arr;
        fs.readFile("/my/path/", 'utf8' ,(err, data) => {
            arr = parsing(data);
            arr.splice(-1,1);


      });
        return arr;
    }

It keeps returning undefined. Even though arr inside the readFile brackets gives me an array...

The possible duplicate discusses printing whereas I need a value to use somewhere else. How can I use the value arr in another function/module?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
MarkJ
  • 411
  • 1
  • 9
  • 23

2 Answers2

0

readFile is async function you need to do this

function final(){
        var arr;
        fs.readFile("/my/path/", 'utf8' ,(err, data) => {
            arr = parsing(data);
            arr.splice(-1,1);
            return arr;
        });

}
Farhan Yaseen
  • 2,507
  • 2
  • 22
  • 37
0

or pass a callback function to final function

function callback(arr) {
//do something with arr
}

function final(callback) {
    var arr;
    fs.readFile("/my/path/", 'utf8' ,(err, data) => {
        arr = parsing(data);
        arr.splice(-1,1);
        callback(arr);
    });
} 

As @Farhan Yassen's answer won't result correct behavior due to the async nature.

And also, you can always use synchronous version of the readFile with readFileSync

gayanch
  • 5
  • 1