Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
83
rated 0 times [  86] [ 3]  / answers: 1 / hits: 112226  / 14 Years ago, fri, november 19, 2010, 12:00:00

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



For example, I want to do exports.x = y; only if it’s running under Node.js. How can I perform this test?






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?


More From » node.js

 Answers
9

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.


[#94906] Wednesday, November 17, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brynnleslis

Total Points: 425
Total Questions: 100
Total Answers: 115

Location: Wallis and Futuna
Member since Tue, Mar 30, 2021
3 Years ago
;