Skip to content

Instantly share code, notes, and snippets.

@smikes
Last active January 3, 2016 11:49
Show Gist options
  • Save smikes/8458330 to your computer and use it in GitHub Desktop.
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'
$ 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
// demonstrate that node-detection code works even
// when require'd as a module
require('./test-browser');
<!doctype html>
<html>
<head>
</head>
<body>
</body>
<script src="test-browser.js"></script>
</html>
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