Languages
[Edit]
EN

JavaScript - detect if *.js code is run under Browser or Node.js

6 points
Created by:
Blessing-D
574

In this short article, we would like to show how to check in a simple way if JavaScript source code is run under Browser or Node.js.

Quick solution: put the following code at the beginning of your program.

Node.js output:

Node.js detection in JavaScript.

 

Note: there are additional alternative ways how to do a more precise JavaScript environment detection, e.g. by checking other global objects: document, location, processprocess.release.name, etc.

More precise detection could be useful when we do detection, not at the script beginning and global objects can be created in the code.

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join