简体   繁体   中英

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

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?

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

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

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 = { ... };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM