-1

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");
    }
  };
  • Possible duplicate of [What is the purpose of Node.js module.exports and how do you use it?](https://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it) – cullanrocks Sep 05 '19 at 16:33
  • There's literally a thousand identical questions on stackoverflow. Did you try searching for your question before you asked? – cullanrocks Sep 05 '19 at 16:33

1 Answers1

0

Are you exporting and importing the function ?

// yourfilename.js

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

utils.mediaRecorderPrompt();
cullanrocks
  • 457
  • 4
  • 16
  • I'm talking about ES6 modules, not CommonJS, and I know the syntax to export and import modules. What I want to know is... take for example that when the function mediaRecorderPrompt() get called it returns mediaRecorder, is it safe? Because this way mediaRecorder is used both inside and outside the module and there can be conflicts. – Alberto Fabbri Sep 05 '19 at 17:12
  • None of your functions are returning anything so I don't know what you are talking about. – cullanrocks Sep 05 '19 at 17:36