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.