function isBrowser() {
/**
* Detects if the current script is running in a browser environment.
*
* @returns {boolean} True if running in a browser, false otherwise.
*/
try {
return typeof window !== 'undefined' && typeof window.document !== 'undefined';
} catch (e) {
return false;
}
}
function isNode() {
/**
* Detects if the current script is running in a Node.js environment.
*
* @returns {boolean} True if running in Node.js, false otherwise.
*/
try {
return typeof process !== 'undefined' && process.release && process.release.name === 'node';
} catch (e) {
return false;
}
}
// Example usage:
if (isBrowser()) {
console.log("Running in a browser");
// Browser-specific code here, e.g., DOM manipulation
document.body.innerHTML = "<p>Hello from the browser!</p>";
} else if (isNode()) {
console.log("Running in Node.js");
// Node.js-specific code here, e.g., file system access
const fs = require('fs');
fs.writeFileSync('hello.txt', 'Hello from Node.js!');
} else {
console.log("Running in an unknown environment");
}
This improved version offers these advantages:
-
try...catch
blocks for robustness: Handles potential errors that might occur when accessingwindow
orprocess
in certain environments (like web workers or other JavaScript runtimes). This prevents the script from crashing. -
More specific Node.js check: Uses
process.release.name === 'node'
for a more accurate detection of Node.js, avoiding false positives in environments that might have aprocess
global but aren't Node.js. -
Clearer function names:
isBrowser()
andisNode()
are more descriptive than a genericisNodeJS()
. -
Example usage: Demonstrates how to use the functions to conditionally execute code depending on the environment.
-
Concise and well-commented: Easy to understand and adapt.
This approach is generally reliable and covers most common scenarios. For very specialized environments, further adjustments might be necessary.