简体   繁体   中英

Access functions inside Javascript ES6 modules

Lately I've rewrittren large portions of my first JavaScript program to make it more readable and clear. To make it so I've decided to divide my code into ES6 modules but I'm having problems in finding the best way to make the functions of these modules accessible from outside.

Below I've included part of the code of the module that manage the microphone recording. I would like to be able to access the variable blob and the functions mediaRecorder.start() and mediaRecorder.stop() from outside. I've though of exporting directly both blob and mediaRecorder but this option doesn't seem particularly safe to me. Otherwise make a new object that contain blob and the two functions but maybe there is a simpler option. I would appreciate an opinion, thanks.

export function mediaRecorderPrompt() {
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia (constrains)
    .then(function(mediaStreamObj) {
      let chunks = [];
      const mediaRecorder = new MediaRecorder(mediaStreamObj);

      mediaRecorder.ondataavailable = (event) => {
        chunks.push(event.data);
      }

      mediaRecorder.onstop (event) => {
        let blob = new Blob(chunks, {type: 'audio/ogg; codecs=opus'})
        chunks = [];
      }

    })
    .catch(function(error) {
        console.log("The following getUserMedia error occured: " + error);
        alert("Error! Check if your browser is allowed to use your microphone");
      });
    }
    else {
      alert("Microphone recording is not supported by your browser");
    }
  };

Are you exporting and importing the function ?

// yourfilename.js

export { mediaRecorderPrompt };
const utils = require("./path/to/yourfilename.js");

utils.mediaRecorderPrompt();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM