Categories
JavaScript Answers

How to check whether a script is running under Node.js?

Spread the love

Sometimes, we want to check whether a script is running under Node.js.

In this article, we’ll look at how to check whether a script is running under Node.js.

How to check whether a script is running under Node.js?

To check whether a script is running under Node.js, we can check if window is undefined.

For instance, we write

if (typeof window === "undefined") {
  exports.foo = {};
} else {
  window.foo = {};
}

to check if window is undefined with typeof window === "undefined".

If it’s undefined, then the script isn’t running in the browser.

Conclusion

To check whether a script is running under Node.js, we can check if window is undefined.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *