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?
Solution 1:
A couple of ideas:
You can check for the window global object, if it is available then you are in a browser
if (typeofwindow === '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
Solution 2:
There is an npm package just for this and it can be used both on client-side and server-side.
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 :)
Solution 3:
You check for the exports
variable, like this:
if (typeofexports=== 'object') {
// Node. Does not work with strict CommonJS, but// only CommonJS-like environments that support module.exports,// like Node.module.exports = { ... };
}
Post a Comment for "How To Detect If Script Is Running In Browser Or In Node.js?"