Search code examples
javascriptnode.jsmodulelogicdetection

In node.js is `module` always an object?


When I see examples of how to detect whether a script in running in node vs. running in the browser, I see logic like:

if (typeof module !== 'undefined' && module.exports) {
    // do something that applies to node
} else {
    // do something that applies to browser
}

The node docs list the global module as being an {Object} which I believe means that typeof module should always be "object". Is that always correct in node? If so doesn't it make more sense to do detection logic like:

if (typeof module === 'object' && module.exports) {
    // do something that applies to node
} else {
    // do something that applies to browser
}

Solution

  • Yes, in all node versions so far, module has always been an object, and is likely to stay that way for all the 0.x versions. As to whether it makes sense to check for it being specifically an object as opposed to not undefined, it's a matter of style mostly. In the former example, since the code is probably only really concerned with adding properties to module.exports, it is more expressive and less brittle as coded. For example, in a future version of node, maybe module becomes a function. In that case, the former example still works whereas the latter example needs a minor change.