Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

javascript - 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.

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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') {
    exports.foo = {};

} else {
    window.foo = {};
}

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.

EDIT

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) { 

See: https://github.com/ry/node/blob/master/src/node.js#L325

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...