1

What is the best way for Javascript code to tell whether it is running in a browser or in NodeJS?

I'm looking for something which will evaluate to a boolean.

Trying to access window and catching the exception seems rather clinky. Is there a better way?

fadedbee
  • 42,671
  • 44
  • 178
  • 308
  • No exception involved; `nodal = (typeof window === 'undefined');` – Alex K. Nov 04 '14 at 15:32
  • Why don't you check process.version which in node gives the following output: { http_parser: '1.0', node: '0.10.4', v8: '3.14.5.8', ares: '1.9.0-DEV', uv: '0.10.3', zlib: '1.2.3', modules: '11', openssl: '1.0.1e' } – matteo Nov 04 '14 at 15:34
  • Here's the block we use for Node/AMD/Browser detection ([link](https://github.com/geraintluff/tv4/blob/master/tv4.js#L10-L19)) - instead of a boolean (there are more than two kinds of setup), it calls the initialisation function in different configurations. – cloudfeet Nov 04 '14 at 15:34
  • http://timetler.com/2012/10/13/environment-detection-in-javascript/ – Cory Danielson Nov 04 '14 at 16:07

2 Answers2

4

You could use a cut down version of the UMD method:

var isNode = (typeof exports === 'object') ? true: false;
Andy
  • 61,948
  • 13
  • 68
  • 95
0
var isNode = (typeof processs != 'undefined' && typeof process.versions != 'undefined' && typeof process.versions.node != 'undefined');
matteo
  • 1,635
  • 1
  • 15
  • 26