3

I am attempting to make a javascript library which I would prefer to be compatible with both browsers and node. However, there is some functionality offered in the node API that isn't offered in browsers (such as compression). I know it would be possible to code this functionality in javascript so it would be cross-compatible, but the node native compression will probably perform much better as it is much lower level.

How should I split between browser-compatible code and code that uses node API?

The way I see it, I could do one of the following:

  • make 2 separate scripts, one for node and one for browsers
  • make my code figure out the environment it is in and act accordingly
  • make all my code the same, but lose some performance improvements I would have had in node

What should I do to solve this?

mghicks
  • 1,144
  • 6
  • 16
Matt Bell
  • 341
  • 1
  • 10
  • 2
    My preference is your first suggestion. My second preference is your second suggestion. I wouldn't do the third. – nnnnnn Feb 12 '12 at 05:25
  • I would probably use RequireJS and its Node adapter. This would allow me to share at least some of the code. – Juho Vepsäläinen Feb 12 '12 at 09:32
  • @nnnnnn I'm interested in finding a solution to this problem, too. Is there any way to ensure that a Javascript library works with multiple Javascript implementations (such as Rhino, Node.js, and browser-side Javascript)? – Anderson Green Dec 10 '12 at 23:47
  • Use https://github.com/component/component. no asynchronous crap. you could also abstract the browser incompatible parts (ie node zlib for compression, a browser compatible version for the browser) or just add a shim – Jonathan Ong Dec 13 '12 at 20:21
  • Could this question help? http://stackoverflow.com/questions/3225251/how-can-i-share-code-between-node-js-and-the-browser – starbeamrainbowlabs Apr 10 '13 at 07:00

1 Answers1

4

I know this is an old question, however, today it is possible easily with Browserify. Browserify lets you write nodejs modules with require() syntax and have them converted to browser complain code easily!

They even ported zlib which you mention to work with it, so that dependency is OK.

I hope this helps future readers, browserify helped me :)

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504