Node vs Browser JavaScript
The language is the same, but the available features differ.
Node.js and the browser both run JavaScript, but each provides a different set of tools around the language.
| Feature | Browser | Node.js |
|---|---|---|
| Global object | window | global |
The DOM (document) | Yes | No |
| File system access | No | Yes (fs) |
| Modules | ES modules | CommonJS & ES modules |
The shared core
Variables, functions, arrays, objects, promises, and all the JavaScript syntax you know work the same in both places. Only the surrounding APIs change.
Example
// This works in Node, but not in a browser:
const os = require('os');
console.log('Running on:', os.platform());
// This works in a browser, but NOT in Node:
// document.querySelector('h1').textContent = 'Hi';When to use it
- A developer migrating a browser utility to Node.js discovers `window` is undefined and guards with `typeof window !== 'undefined'`.
- A team shares validation logic between an Express backend and a React frontend by keeping it free of DOM or Node-specific imports.
- A Node.js script uses `process.env` and `fs` -- APIs absent in browsers -- to read secrets and write reports to disk.
More examples
Node-only globals
Shows three globals that are available only in Node.js, not in browser JavaScript.
// These exist in Node but NOT in the browser
console.log(process.version); // Node version
console.log(__filename); // absolute path of this file
console.log(__dirname); // directory of this fileBrowser globals absent in Node
Illustrates that DOM globals like `window`, `document`, and `localStorage` do not exist in Node.js.
// Running this in Node.js (pre-18):
typeof window; // 'undefined'
typeof document; // 'undefined'
typeof localStorage; // 'undefined'Isomorphic environment check
A portable runtime detection pattern used in libraries that target both Node.js and the browser.
// shared/env.js -- works in both Node and browser
const isNode =
typeof process !== 'undefined' &&
process.versions != null &&
process.versions.node != null;
console.log(isNode ? 'Running in Node' : 'Running in browser');
Discussion