Languages
[Edit]
EN

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

6 points
Created by:
Blessing-D
274

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.

// ONLINE-RUNNER:browser;

"use strict"

const IS_NODE = typeof global === 'object' && '[object global]' === global.toString.call(global);
const IS_BROWSER = typeof window === 'object' && '[object Window]' === window.toString.call(window);

console.log(`IS_NODE: ${IS_NODE}`);
console.log(`IS_BROWSER: ${IS_BROWSER}`);

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.

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