1

I have a script.js that I either use on client side html page. Either via nodejs.

How can I get a function to fire only if the script is run via nodejs ?

1

2 Answers 2

1

Queue.js handles it such:

if (typeof define === "function" && define.amd) define(function() { return queue; });
else if (typeof module === "object" && module.exports) module.exports = queue;
else this.queue = queue;

Underscore does something such :

  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }

But this seems to assess node.modules. Secondly, if someone could confirm what each case is, that would help !

Sign up to request clarification or add additional context in comments.

Comments

1

fabric.js has a useful one-liner:

var isLikelyNode = typeof Buffer !== 'undefined' && typeof window === 'undefined';

1 Comment

None of the answers solved my case. Indeed, i am creating a virtual windows via jsdom, so my js script always is in a browser, real or virtual. I haven t tested these answers for strickly serverside use cases. So i can neither valid your, nor my answer. But I can +1 some of your answer so you get to 2000 points :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.