Monday, 15 May 2017

Why does "fs.readFile" callback log file data to the console but not return the same data

I'm writing a script which will open all of the bookmarks I put in a particular folder. I'm using "fs" module's "readFile" method to get the data from the bookmarks file, and some utility methods to drill the data down and construct an array of urls to open.

The trouble I am having is that though the file data is accessable, and I can manipulate it with the other methods in my class, I do not seem to be able to return the result from the "fs.readFile" callback. Here is the code (I can add the rest of the class as well if someone would find that helpfull)

readBookmarks() {
    fs.readFile(homeDir() + "/Library/Application " + "Support/Google/Chrome/Default/Bookmarks",
        (error, data) => {
        if (error) {
            throw error;
        }
        if (data){
            console.log(this.constructUrlList(data)); //outputs an array of urls like I expect
            return this.constructUrlList(data); // returns undefined
        }
    });
}

I feel like I'm missing something. I get that "fs.readFile" is async, but should the callback only fire once the file buffer is loaded? And if not why is the data available to "console.log"?

Thanks for help



via HelloWorld

No comments:

Post a Comment