如何从存档文件中的 json 中读取特定值。使用 javascript 和 jszip

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

我正在使用 jszip 从 zip 文件中读取 json 文件。我可以打开它并从我的函数中获取我想要的信息到控制台。但是,我无法从 javascript 函数中获取该信息。也许我做错了。平时不用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'));

问题是您在回调内部返回,所以您没有在实际函数中返回。解决方案是使用 async/await 代替:

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")
  );
})()

注意我已经导入了 util 模块来将 fs.readFile 变成一个更适合 async/await 的函数 :)