54

I have jasmine test spec file and I want to run it using both node.js and in browser. How can I detect if script is running in node?

jcubic
  • 61,973
  • 54
  • 229
  • 402

3 Answers3

76

A couple of ideas:

You can check for the window global object, if it is available then you are in a browser

if (typeof window === 'undefined')
// this is node

Or you can check for the process object, if it is available then you are in node

if(typeof process === 'object')
// this is also node
Hisham
  • 2,586
  • 1
  • 14
  • 18
  • 14
    I found that many proposed solutions stop working if the code has been webpack'd, because webpack defines all kinds of `process`, `module`, `require`, etc symbols. `window` usually still works, unless of course you additionally also want to detect being run from a webworker, where there is no `window`. – jlh Nov 06 '18 at 21:27
  • 2
    the check on `window` will not worker inside a WebWorker ... :) however, the check against `process` will work canonically in all environments afaiu – Tchakabam Nov 25 '19 at 15:19
  • 1
    another idea, to avoid checking on `process` in the browser: the global var `self` is an alternative to using `window` (but is equivalent to it in main thread) and refers to the global worker scope otherwise. – Tchakabam Nov 25 '19 at 15:21
  • 1
    example: `if (typeof self === 'undefined') { /* neither web window nor web worker */ }` – Tchakabam Nov 25 '19 at 15:22
  • As of 2021, Firefox browser has an object on the root called `process`, so the second method doesn't work unless you also check for the `title` attribute like this; `typeof process === 'object' && process.title === 'node'` – Jivings Nov 05 '21 at 10:43
  • `process.title === 'node'` does not work when node.js is started with an absolute path or the binary is renamed. – umitu Nov 15 '21 at 15:52
21

There is an npm package just for this and it can be used both on client-side and server-side.

browser-or-node

You can use it in your code like this

import { isBrowser, isNode } from 'browser-or-node';

if (isBrowser) {
  // do browser only stuff
}

if (isNode) {
  // do node.js only stuff
}

Disclaimer: I am the author of this package :)

Dinesh Pandiyan
  • 5,814
  • 2
  • 30
  • 49
-1

You check for the exports variable, like this:

if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = { ... };
}
Joost Vunderink
  • 1,178
  • 6
  • 14
  • For this to work, you'll need to make sure you don't have `window.exports` set in the browser, or else this duck-typing will fail. – Josh Beam Dec 31 '15 at 19:38