Detect Node is a lightweight JavaScript library that provides reliable Node.js environment detection. It accurately determines whether code is running in a Node.js environment versus a browser or other JavaScript runtime by checking if the global process variable has the specific [[Class]] of 'process' unique to Node.js.
npm install detect-nodeconst isNode = require('detect-node');For ES modules:
import isNode from 'detect-node';const isNode = require('detect-node');
if (isNode) {
console.log("Running under Node.js");
// Node.js-specific code here
const fs = require('fs');
fs.readFileSync('config.json');
} else {
console.log("Running in browser or other environment");
// Browser-specific code here
document.getElementById('app');
}Detect Node uses a unique detection approach that avoids common pitfalls of other environment detection methods:
Object.prototype.toString.call() to check the [[Class]] property of the process objectprocess in a way that causes bundlers to include Node.js polyfillsprocess is undefinedDetects whether the current JavaScript environment is Node.js by checking for the unique [[Class]] property of the Node.js process object.
/**
* Boolean indicating whether the current environment is Node.js
* Returns true if running in Node.js, false otherwise
*/
const isNode; // booleanThe detection logic uses:
Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'Module Formats:
index.js): module.exports = [detection logic]index.esm.js): export default [detection logic]browser.js): module.exports = false (always returns false for browser builds)Usage Examples:
// CommonJS
const isNode = require('detect-node');
if (isNode) {
// Use Node.js APIs
const path = require('path');
const __dirname = path.dirname(__filename);
}
// ES Modules
import isNode from 'detect-node';
if (isNode) {
// Use Node.js APIs
import { readFile } from 'fs/promises';
const data = await readFile('data.txt', 'utf8');
}
// Conditional imports based on environment
if (isNode) {
const nodeSpecificModule = await import('./node-version.js');
} else {
const browserSpecificModule = await import('./browser-version.js');
}Build Tool Integration:
The package is designed to work seamlessly with build tools:
browser field in package.json to automatically substitute browser.js for client bundlesError Handling:
The detection is safe and will never throw errors:
typeof process !== 'undefined' check to avoid ReferenceError0 if process is undefinedfalse for any non-Node.js environment