如何检查脚本是否在node.js下运行? [英] How to check whether a script is running under node.js?
本文介绍了如何检查脚本是否在node.js下运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个node.js脚本的脚本,我想让javascript引擎保持独立。
I have a script I am requiring from a node.js script, which I want to keep javascript engine independent.
所以,例如,我想做:
exports.x = y;
我该如何执行此测试?
编辑:发布此问题时,我不知道node.js模块功能是基于 commonjs 。
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:
脚本如何判断是否需要将其作为commonjs模块?
How can a script tell whether it has been required as a commonjs module?
推荐答案
通过寻找CommonJS支持,这就是 Underscore.js 库就可以了:
By looking for CommonJS support, this is how the Underscore.js library does it:
编辑:更新的问题:
(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.
这篇关于如何检查脚本是否在node.js下运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文