0

I have been trying to do write a function that works both in node and the browser, but in each case it has to load different external libraries, to finally do the same processing (in the end the output would be the same.)

How would I go about doing it? This is a more in-detail explanation:

  • Write a function that accepts an image
  • if the environment is node (currently user sets an argument to "node" or "browser") it loads some stuff
  • if the env is browser, it does some other stuff

I want that either a NodeJS user, or a Browser user could load it, and the function would run the right code.

I know it may be a bit vague but I can add any information. A very simple example is below:

export async function greeting(browserOrNode){
if(browserOrNode==="browser"){
  //run X code supported in browser
 } else{ 
  const { myHelper } = await import("./helpers")
  // run code supported in node 
 }
}

Is there any other way I should be thinking on doing it?

Another option I considered was to export two functions one myFnForBrowser another one myFnForNode but I am not sure whether that is professional.

Minsky
  • 2,277
  • 10
  • 19
  • Are you looking for `inBrowser = !!window`? – ControlAltDel Jan 17 '23 at 21:34
  • It's not clear what you are asking. We have a cornucopia of questions about how to determine whether code is running in the browser or NodeJS. If you want that, we can provide many answers. If you want to know how to do it "professionally", first you'll have to define what that word means objectively, then we could possibly answer it. Otherwise, this question appears to be asking for opinions, which are not well served by Stack Overflow. – Heretic Monkey Jan 17 '23 at 21:39
  • @HereticMonkey I am pondering more of an architectural question. If my script is supposed to run both in browser and node, would it make sense to have one file for both or one file for each ? The library I am load, specifically for Node, is node-canvas. Thanks you, I will also update the post. – Minsky Jan 17 '23 at 21:43
  • @ControlAltDel wouldn't that just error in node as `window` doesn't exist ? I tried in the REPL and errored out – Minsky Jan 17 '23 at 21:45
  • `wouldn't that just error in node` you can use this fact to do detection `try { .... } catch () { /* obviously not a browser */ }`. Alternatively there are many ways to avoid the error such as using `typeof` – slebetman Jan 18 '23 at 01:36

0 Answers0