Environment detection: node.js or browser

后端 未结 8 1955
误落风尘
误落风尘 2020-11-29 20:54

I\'m developping a JS-app that needs to work both on the client side and the server side (in Javascript on a browser and in Node.js), and I would like to be able to reuse th

相关标签:
8条回答
  • 2020-11-29 21:21

    Simple condition from pdf.js

    Second condition variant process.constructor.name === 'process'

    src/shared/is_node.js:

    /* Copyright 2018 Mozilla Foundation
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *     http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */
    /* globals process */
    
    // NW.js / Electron is a browser context, but copies some Node.js objects; see
    // http://docs.nwjs.io/en/latest/For%20Users/Advanced/JavaScript%20Contexts%20in%20NW.js/#access-nodejs-and-nwjs-api-in-browser-context
    // https://www.electronjs.org/docs/api/process#processversionselectron-readonly
    // https://www.electronjs.org/docs/api/process#processtype-readonly
    const isNodeJS =
      typeof process === "object" &&
      process + "" === "[object process]" &&
      !process.versions.nw &&
      !(process.versions.electron && process.type && process.type !== "browser");
    
    export { isNodeJS }; 
    
    0 讨论(0)
  • 2020-11-29 21:36

    I know this is a late answer to a (1.5 year) old question but why not copy jQuery's source code?

    if (typeof module === "object" && typeof module.exports === "object") {
      // node
    }
    
    if (typeof window !== "undefined" && typeof window.document !== "undefined") {
      // browser
    }
    

    Good luck.

    0 讨论(0)
  • 2020-11-29 21:38

    There is an npm package just for this and it can be used both on client-side and server-side.

    browser-or-node

    You can use it this way

    if (isBrowser) {
      // do browser only stuff
    }
    
    if (isNode) {
      // do node.js only stuff
    }
    

    Disclaimer: I am the author of this package :)

    0 讨论(0)
  • 2020-11-29 21:41

    Since apparently Node.js could have both (w/ NW.js?), my personnal way to do it is by detecting if the node entry exists in process.versions object.

    var isNode = false;    
    if (typeof process === 'object') {
      if (typeof process.versions === 'object') {
        if (typeof process.versions.node !== 'undefined') {
          isNode = true;
        }
      }
    }
    

    The multilevel of conditions is to avoid errors while searching into an undefined variable due to some browsers limitations.

    Reference: https://nodejs.org/api/process.html#process_process_versions

    0 讨论(0)
  • 2020-11-29 21:41

    You can attach to variable window or global - based on situation. Though it is not a recommended way of making multi-platform JS application:

    var app = window ? window : global;
    

    It is much better to have your global variable, that will be used over logic of application, but will be made of parts of based on different platforms. Something like:

    var app = {
        env: '',
        agent: ''
    };
    
    if (window) {
        app.env = 'browser';
        app.agent = navigator.userAgent;
    } else if (process) {
        app.env = 'node';
    }
    

    So the idea is that your main application logic will be absolutely the same and will use same object, only that global object have to be changed based on environment. That makes your application much more portable and flexible in terms of platforms.

    0 讨论(0)
  • 2020-11-29 21:41
    <script type=module>
    /*
    detect global/window/self in browser, deno, nodejs
    including where 'this' is undefined
    */
    const self = new Function('return this')();
    console.log( 
        (self.window && "window" || self.global && 'global'),
        self.toString().slice('[object '.length, -1).toLowerCase()
    );
    /*
    browser: window window
    nodejs: global global
    deno: window object
    */
    </script>
    
    0 讨论(0)
提交回复
热议问题