Last active
January 3, 2016 11:49
-
-
Save smikes/8458330 to your computer and use it in GitHub Desktop.
Snippet to detect node vs. browser, does not use typeof, does not use 'in'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ node tb-harness.js | |
running under node | |
$ node test-browser.js | |
running under node | |
Chrome console reports | |
running in a browser test-browser.js:13 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// demonstrate that node-detection code works even | |
// when require'd as a module | |
require('./test-browser'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
</head> | |
<body> | |
</body> | |
<script src="test-browser.js"></script> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var globalScope = this, | |
isNode = false; | |
(function () { | |
'use strict'; | |
if (!globalScope.hasOwnProperty('window')) { | |
isNode = true; | |
} | |
if (isNode) { | |
console.log('running under node'); | |
} else { | |
console.log('running in a browser'); | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment