Search code examples
javascriptjszip

how to read specific value from json in an archived file. Using javascript ,and jszip


I am reading a json file from within a zip file using jszip. I can open it and get the information that I want into the console from my function. I can't however get that information out of my javascript function. Maybe I am doing it wrong. Don't usually code using js.

const JSZip = require("jszip");
const fs = require("fs"); 
var myReturn;
function readJsons(bookPath,bookName,fileName,filePath,keyOption){
 


   fs.readFile(bookPath + bookName, function(err, data) {

    if (err) throw err;
    
     JSZip.loadAsync(data).then(function (zip) {
     
      // Read the contents of the '.txt' file
        zip.file(filePath + fileName).async("string").then(function (data) {
        var mydata = JSON.parse(data);
          //gets the value of the key entered
        myReturn = JSON.stringify(mydata[0][keyOption]);       //value here should be "test book"
        console.log(myReturn);                  //printed in console is "test book" works to here
        
          return myReturn;
          
      });
     
     
    });
    
   
    
  });
 
   
}
console.log(readJsons('simplelbook.zip','','frontMatter.json','','bookName'));


Solution

  • The problem is that you are returning inside the callback, so you aren't returning in the actual function. The solution would be using async/await instead:

    const JSZip = require("jszip");
    const fs = require("fs");
    const util = require("util"); // require the util module
    
    const readFile = util.promisify(fs.readFile); // transform fs.readFile into a more compatible form
    
    async function readJsons(bookPath, bookName, fileName, filePath, keyOption) {
      try {
        // this part does the same thing, but with different syntax
        const data = await readFile(bookPath + bookName);
        const zip = await JSZip.loadAsync(data);
        const jsonData = await zip.file(filePath + fileName).async("string");
        const mydata = JSON.parse(jsonData);
        const myReturn = JSON.stringify(mydata[0][keyOption]);
    
        return myReturn; // return the data, simple as that
      } catch (e) {
        console.error(e); // error handling
      }
    }
    
    (async () => { // self executing async function so we can use await
      console.log(
        await readJsons("simplelbook.zip", "", "frontMatter.json", "", "bookName")
      );
    })()
    

    Notice I have imported the util module to turn fs.readFile into a function that is more suited for async/await :)