Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if script is running in browser or in Node.js? [duplicate]

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?

like image 377
jcubic Avatar asked Dec 31 '15 19:12

jcubic


2 Answers

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
like image 70
Hisham Avatar answered Nov 03 '22 09:11

Hisham


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 :)

like image 45
Dinesh Pandiyan Avatar answered Nov 03 '22 09:11

Dinesh Pandiyan