Hugolpz
Hugolpz

Reputation: 18248

How to fire code only when script.js is ran via node.js?

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 ?

Upvotes: 1

Views: 72

Answers (2)

Matt Harrison
Matt Harrison

Reputation: 13567

fabric.js has a useful one-liner:

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

Upvotes: 1

Hugolpz
Hugolpz

Reputation: 18248

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 !

Upvotes: 1

Related Questions