Reading zip file contents and assign it to local variable

孤人 提交于 2021-02-10 17:26:09

问题


I want to read contents of zip file that contains multiple files and merge content from all the files and assign it to local variable. But local variable is not in scope in below code:

const jsZip = require('jszip');
  jsZip.loadAsync(fileList[0]).then(function (zip) {
    Object.keys(zip.files).forEach(function (filename) {
      zip.files[filename].async('string').then(function (fileData) {
         this.fileData = this.fileData + '**$$##$$**' + fileData;
      });
    });
  });

'this' is undefined here because this is executing in context with jszip. Also tried with 'jszip-sync' but no luck. Your help is appreciated.


回答1:


Just change all function (){} to ()=>{}, Fat Arrow :

const jsZip = require('jszip');
  jsZip.loadAsync(fileList[0]).then((zip) => { // <----- HERE
    Object.keys(zip.files).forEach((filename) => { // <----- HERE
      zip.files[filename].async('string').then((fileData) => { // <----- HERE
         this.fileData = this.fileData + '**$$##$$**' + fileData;
      });
    });
  });

Reason why it is not working : however when you use function() {}, generally it loses the context of root element, to maintain the context, you should use fat arrow.

You can find many great articles about fat arrow, I have just provided one of them.

Until arrow functions, every new function defined its own this value (based on how function was called, a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming. More in detail



来源:https://stackoverflow.com/questions/51925056/reading-zip-file-contents-and-assign-it-to-local-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!