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(path.join(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
UPDATE: Thanks to reading the dup jfriend00 posted I now understand a good pattern for modular, asynchronous js. Here is the refactored code:
openLinks() {
this.readBookmarks().then((data) => {
const urlList = this.constructUrlList(data);
for(let url of urlList) {
opn(url, {app: 'Safari'});
}
process.exit();
}).catch((error) => {
console.error("Unable to read the file due to error: " + error.stack);
})
}
readBookmarks() {
return new Promise((resolve, reject) => {
fs.readFile(path.join(homeDir(), "/Library/Application Support/Google/Chrome/Default/Bookmarks"),
(error, data) => {
error ? reject(error) : resolve(data);
});
});
}