写个方法判断当前脚本运行在浏览器还是node环境中

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 accessing window or process 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 a process global but aren't Node.js.

  • Clearer function names: isBrowser() and isNode() are more descriptive than a generic isNodeJS().

  • 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.

posted @   王铁柱6  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示