I'm developping a JS-app that needs to work both on the client side and the server side (in Javascript on a browser and in Node.js), and I would like to be able to reuse the parts of the code that are used for both sides.
I have found out that window
was a variable only accessible on Browsers, and global
in node, so I can detect in which environment the code is executing (assuming that no script declares the window
variable)
They are two problems.
How should I detect in which browser the code is running. For example, is this code OK. (This code is inline, meaning that it is surrounded by some global code, reused for both environments)
if window? totalPath= "../examples/#{path}" else totalPath= "../../examples/#{path}"
How can I use global variables for both environments ? Now, I'm doing the following, but this really doesn't feel right.
if window? window.DocUtils = {} window.docX = [] window.docXData= [] else global.DocUtils= {} global.docX = [] global.docXData = []