JavaScript in the Browser vs Node.js
JavaScript can run in two main environments — the browser and Node.js. Although the core language remains the same, the capabilities, context, and available APIs are different in each environment.
1. Runtime Environment
Browser: JavaScript runs inside web browsers like Chrome, Firefox, and Edge. It is mainly used for interacting with web pages and handling user interactions.
Node.js: Node.js is a JavaScript runtime built on Chrome’s V8 engine. It allows JavaScript to run outside the browser, typically on servers or backend applications.
2. Access to Global Objects
Try this in both environments and compare:
// In browser
console.log(window === globalThis);
Output:
true
// In Node.js
console.log(global === globalThis);
Output:
true
In the browser, the global object is window
. In Node.js, it's global
. But both environments also support the standardized globalThis
.
3. File System Access
Can we access local files from JavaScript?
Yes — but only in Node.js.
Try this Node.js-only example:
// Node.js
const fs = require('fs');
fs.writeFileSync('hello.txt', 'Hello from Node.js');
console.log('File created');
Output:
File created
Browsers do not allow file system access for security reasons.
4. APIs Available
Browser: Includes access to Web APIs like fetch
, localStorage
, document
, alert
.
Node.js: Includes APIs for fs
(file system), http
(server), os
(system info), etc.
Example: Using Fetch vs HTTP Module
In Browser:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(data => console.log(data));
In Node.js: (Before v18, Node didn’t support fetch by default)
const https = require('https');
https.get('https://jsonplaceholder.typicode.com/posts/1', res => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => console.log(JSON.parse(data)));
});
5. Modules
How do we import/export code?
In browsers, you need to use ES6 modules (with type="module"
in HTML). In Node.js, both CommonJS (require
) and ES Modules (import
) are supported.
// Node.js (CommonJS)
const os = require('os');
console.log(os.platform());
6. Real-World Use
- Use the browser when building UI, web apps, and client-side interactivity.
- Use Node.js when building servers, APIs, CLI tools, and backend logic.
Frequently Asked Questions
Q: Can we use Node.js features like fs
in the browser?
A: No. Browsers block direct access to the file system for security. That’s why you need Node.js for such tasks.
Q: Can I write the same code for both environments?
A: Yes, if you're using pure JavaScript logic (e.g., math operations, array manipulation). But environment-specific APIs like document
or fs
are not cross-compatible.
Conclusion
Understanding the differences between JavaScript in the browser and Node.js is key to writing environment-specific applications. Both are powerful and essential to modern JavaScript development, but their roles are distinct.