写个方法判断当前脚本运行在浏览器还是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 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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了