What is detect-node?
The detect-node npm package is a simple utility that allows developers to determine if their JavaScript code is running in a Node.js environment as opposed to a browser environment. This can be useful for writing isomorphic code that behaves differently depending on where it is executed.
What are detect-node's main functionalities?
Node.js environment detection
This feature allows the developer to check if the code is running in Node.js. The package exports a boolean value that is true if the environment is Node.js and false otherwise.
const isNode = require('detect-node');
if (isNode) {
console.log('Running in Node.js');
} else {
console.log('Running in the browser');
}
Other packages similar to detect-node
is-node
is-node is a package similar to detect-node that provides a simple check to see if the code is running in Node.js. It compares to detect-node by offering the same basic functionality but may have different implementation details or additional features.
is-node-process
is-node-process is another package that serves the same purpose as detect-node. It checks if the current process is a Node.js process. The difference may lie in the specific method of detection and any additional checks or features it provides.
Install
npm install --save detect-node
Usage:
var isNode = require('detect-node');
if (isNode) {
console.log("Running under Node.JS");
} else {
alert("Hello from browser (or whatever not-a-node env)");
}
The check is performed as:
module.exports = false;
try {
module.exports = Object.prototype.toString.call(global.process) === '[object process]'
} catch(e) {}
Thanks to Ingvar Stepanyan for the initial idea. This check is both the most reliable I could find and it does not use process
env directly, which would cause browserify to include it into the build.