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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With