Read a file synchronously in Javascript

前端 未结 6 459
无人及你
无人及你 2020-12-08 01:49

I would like to read a file and convert it into a base64 encoded string using the FileReader object. Here\'s the code I use :


    var reader = new FileReader();
         


        
6条回答
  •  轮回少年
    2020-12-08 02:47

    The below code works sync way to read the file and return its content as text (string)

     function SyncFileReader(file) {
        let self = this;
        let ready = false;
        let result = '';
    
        const sleep = function (ms) {
          return new Promise(resolve => setTimeout(resolve, ms));
        }
    
        self.readAsDataURL = async function() {
            while (ready === false) {
              await sleep(100);
            }
            return result;
        }    
    
        const reader = new FileReader();
        reader.onloadend = function(evt) {
            result = evt.target.result;
            ready = true;
        };
        reader.readAsDataURL(file);
      }
    

    Usage :

    const fileReader = new SyncFileReader(file);
    const arrayBuffer = await fileReader.readAsDataURL();
    

提交回复
热议问题