How to check whether a script is running under node.js?


I have a script I am requiring from a node.js script, which I want to keep javascript engine independent.

So, for example, I want to do:

exports.x = y;

only if it's running under node.js. how can I perform this test?

Edit: When posting this question, I didn't know the node.js modules feature is based on commonjs.

For the specific example I gave a more accurate question would've been:

How can a script tell whether it has been required as a commonjs module?

11/19/2010 11:52:47 AM

Accepted Answer

By looking for CommonJS support, this is how the Underscore.js library does it:

Edit: to your updated question:

(function () {

    // Establish the root object, `window` in the browser, or `global` on the server.
    var root = this; 

    // Create a reference to this
    var _ = new Object();

    var isNode = false;

    // Export the Underscore object for **CommonJS**, with backwards-compatibility
    // for the old `require()` API. If we're not in CommonJS, add `_` to the
    // global object.
    if (typeof module !== 'undefined' && module.exports) {
            module.exports = _;
            root._ = _;
            isNode = true;
    } else {
            root._ = _;

Example here retains the Module pattern.

11/14/2018 12:41:52 PM

Well there's no reliable way to detect running in Node.js since every website could easily declare the same variables, yet, since there's no window object in Node.js by default you can go the other way around and check whether you're running inside a Browser.

This is what I use for libs that should work both in a Browser and under Node.js:

if (typeof window === 'undefined') { = {};

} else { = {};

It might still explode in case that window is defined in Node.js but there's no good reason for someone do this, since you would explicitly need to leave out var or set the property on the global object.


For detecting whether your script has been required as a CommonJS module, that's again not easy. Only thing commonJS specifies is that A: The modules will be included via a call to the function require and B: The modules exports things via properties on the exports object. Now how that is implement is left to the underlying system. Node.js wraps the module's content in an anonymous function:

function (exports, require, module, __filename, __dirname) { 


But don't try to detect that via some crazy arguments.callee.toString() stuff, instead just use my example code above which checks for the Browser. Node.js is a way cleaner environment so it's unlikely that window will be declared there.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow