How to determine if a script works in a browser or in Node.js?

I have a spec spec spec for jasmine and I want to run it using both node.js and the browser. How to determine if a script is running in node?

+4
source share
3 answers

A few ideas:

You can check the global window object, if available, you are in the browser

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

Or you can check the process object, if available, you are in node

if(typeof process === 'object')
// this is also node
+8
source

There is an npm package for this and it can be used both on the client side and on the 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 :)

0

exports, :

if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = { ... };
}
-1

Source: https://habr.com/ru/post/1622377/


All Articles