Search code examples
javascripthtmlinputfetch

I want to fetch a file from my code folder to my js file automatically when the page loads


I want to fetch a file from my code folder to my js file automatically when the page loads so I can use in an audio visualizer. I don't have to fetch it from the users computer!

How do I do it? I was trying to do it using fetch but I can only fetch from URLs now. I want to use the file like this

    document.getElementById('file').addEventListener('change', function(e){
      this.fileReader.readAsArrayBuffer(e.target.files[0]);
      }.bind(this));
      var _this = this;
    
    this.fileReader.onload = function(){
      _this.audioContext.decodeAudioData(_this.fileReader.result, function(buffer){
        if(_this.source) {
          _this.source.stop();
        }
        _this.source = _this.audioContext.createBufferSource();
        _this.source.buffer = buffer;
        
        _this.source.loop = true;

        _this.source.connect(_this.analyser);

        _this.gainNode = _this.audioContext.createGain();

        _this.source.connect(_this.gainNode);
        _this.gainNode.connect(_this.audioContext.destination);
        _this.source.start(0);
        
        _this.frequencyArray = _this.webgl.sphereG.attributes.aFrequency.array;
        _this.indexPosArray = _this.webgl.indexPosArray;
        _this.indexPosLength = _this.webgl.indexPosArray.length;
        _this.isReady = true;
      });
    };
  }

but instead of getting the user to choose a file from his/her computer I want to fetch a file from my the folder where this code lies automatically.


Solution

  • No need for an <input type="file"/> then.

    You might have success with

    // if the HTML that's executing the current JavaScript is at 
    // https://example.com/foo/index.html and audiofile.ext
    // is in the same location as index.html (i.e. also inside foo),
    // this would work:
    
    fetch('audiofile.ext')
       .then(res => res.blob())
       .then(blob => {
          // do stuff with the blob
       });
    

    See the fetch docs on MDN.