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

在前端开发中,要判断当前脚本是运行在浏览器环境还是Node.js环境中,可以通过检查某些全局对象是否存在来实现。在浏览器环境中,windowdocument 等对象是全局可访问的,而在Node.js环境中,global 对象是全局的,并且通常没有 windowdocument

以下是一个简单的方法,用于判断当前环境是浏览器还是Node.js:

function isRunningInBrowser() {
    // 尝试访问 window 和 document 对象
    // 如果它们都存在且不是 undefined,那么很可能是在浏览器环境中
    return typeof window !== 'undefined' && typeof document !== 'undefined';
}

function isRunningInNode() {
    // 在 Node.js 中,global 对象是全局的
    // 并且 process 对象也是 Node.js 特有的
    return typeof global !== 'undefined' && typeof process !== 'undefined' && process.versions.node;
}

// 使用示例
if (isRunningInBrowser()) {
    console.log('当前脚本运行在浏览器环境中');
} else if (isRunningInNode()) {
    console.log('当前脚本运行在Node.js环境中');
} else {
    console.log('无法确定当前环境');
}

在这个示例中,isRunningInBrowser 函数检查 windowdocument 对象是否存在,如果存在则返回 true,表示当前环境是浏览器。而 isRunningInNode 函数则检查 globalprocess 对象是否存在,并且 process.versions.node 是否有值,如果都满足则返回 true,表示当前环境是Node.js。

请注意,这种方法并不是绝对的,因为有可能在某些特殊的浏览器环境或Node.js环境中,这些全局对象的行为可能会有所不同。但在大多数情况下,这种方法是有效的。

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