webmidi: Node ReferenceError: navigator is not defined

I’m running this code and it throws “ReferenceError: navigator is not defined”

var WebMidi = require('webmidi')
WebMidi.enable(function (err) {

  if (err) {
    console.log("WebMidi could not be enabled.", err);
  } else {
    console.log("WebMidi enabled!");
  }
  
});

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 20 (14 by maintainers)

Most upvoted comments

I made some progress. The code below will let you list input and output devices. It will also let you add listeners on inputs and try outputs.

This is more of a proof-of-concept than anything else. Do not use WebMidi.js + Node in production!

// The `web-midi-api` module takes care of importing the `jazz-midi` module (which needs to be
// installed) and the WebMIDIAPI shim (which is already part of `web-midi-api`).
global.navigator = require('web-midi-api');

// WebMidi.js depends on the browser's performance.now() so we fake it with the `performance-now`
// Node module (which is installed as a dependency of `web-midi-api`).
if (!global.performance) global.performance = { now: require('performance-now') };

// To use WebMidi.js, you then simply need to require it.
var WebMidi = new require('webmidi');

// Usual stuff
WebMidi.enable(function (err) {

  if (err) return console.log("WebMidi could not be enabled.", err);
  console.log("WebMidi enabled!");

  console.log("*** Inputs:");

  WebMidi.inputs.forEach((o) => {
    console.log(o.name)

    o.addListener('noteon',  "all", (event) => {
      console.log(event.note)
    });

  });

  console.log("*** Outputs:");

  WebMidi.outputs.forEach( (o) => {
    console.log(o.name);
    o.playNote("G3");
  });

});

To use this code, you will need at least release 2.0.0-rc.7 of WebMidi.js which includes a tiny but important change.

Super helpful, thanks! Used the global navigator to sign in to AWS-Cognito for testing api with auth. 👍