0

I have a simple javascript function that creates an XMLHttpRequest , runs it (synchronously to make things as simple as possible) and returns an array that is the result.

exports.loadBinFile = function() { ... }

I have that script in a js file, x.js, and I have a matching PureScript file x.purs, and in it:

foreign import loadBinFile :: forall e. Eff (fileLoad :: FILELOAD | e) (Array Int)

All is fine and well regarding that, but I'm using XMLHttpRequest which is a browser object, and when trying to run pulp run, I'm getting an error that XMLHttpRequest is undefined.

I've tried installing an npm package called xmlhttprequest which contains said object, also tried a similar bower package, but both fail.

I'm relatively new to javascript, and I assume the way I'm trying to make things wrong, is outright wrong. What would be the correct way of approaching this?

I figure I can fix this by putting the script inside an .html file, but I want to do this correctly, i.e. having matching .purs and .js files, and letting pulp do it's job.

How should I go about doing this?

Thanks!

PsyFish
  • 287
  • 1
  • 9

1 Answers1

1

You could give purescript-affjax a try, which is based on XHR requests and works both on Node and in the browser.

If you want to continue doing it yourself though, the reason XMLHTTPRequest is still undefined even after installing a package for it via npm is you will also need to require the module it exposes when in node.

We use xhr2 from npm in Affjax as I think we had some trouble with xmlhttprequest, so using that example, in your FFI JS you'll want to use a function something like this:

var newXHR = function () {
  if (typeof module !== "undefined" && module.require) {
    var XHR = module.require("xhr2");
    return new XHR();
  }
  return new XMLHttpRequest();
}

Rather than just attempting to call new XMLHTTPRequest(). You can see something similar although a little more involved in the affjax FFI code.

gb.
  • 4,629
  • 1
  • 20
  • 19
  • Actually, a short while after posting this question I stumbled into Affjax! I had a suspicion this might answer my needs, now that you validated my suspicion, I'll look into it, thanks! About the 'require' I did use require, but with xmlhttprequest from npm, and of course the error wasn't that the object was unknown after that. The error was with setting some undefined attribute (in xmlhttprequest's js file). I'll try xhr2 instead to try and have closure regarding this error. Anyways, It looks like affjax is the proper way to go about this. Thanks! – PsyFish May 07 '16 at 16:39