EN
JavaScript - detect if *.js code is run under Browser or Node.js
6 points
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.
xxxxxxxxxx
1
"use strict"
2
3
const IS_NODE = typeof global === 'object' && '[object global]' === global.toString.call(global);
4
const IS_BROWSER = typeof window === 'object' && '[object Window]' === window.toString.call(window);
5
6
console.log(`IS_NODE: ${IS_NODE}`);
7
console.log(`IS_BROWSER: ${IS_BROWSER}`);
Node.js output:
Note: there are additional alternative ways how to do a more precise JavaScript environment detection, e.g. by checking other global objects:
document
,location
,process
,process.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.