Browser vs Node.js Runtime

Browser Runtime:

// Available in browser
window.alert('Hello');
document.getElementById('button');
localStorage.setItem('key', 'value');
fetch('https://api.example.com');


// NOT available in browser
const fs = require('fs'); // ERROR! 

 Node.js Runtime: 

// Available in Node.js
const fs = require('fs');
const http = require('http');
process.exit(0);


// NOT available in Node.js
window.alert('Hello'); // ERROR!
document.getElementById('button'); // ERROR! 

What Does "Providing a Runtime" Mean?

When we say "Node.js provides a runtime for JavaScript," we mean:

  1. It gives JavaScript a place to run outside the browser
  2. It provides access to system resources (files, network, processes)
  3. It manages memory and execution
  4. It handles errors and crashes
  5. It provides utility functions and modules

Real-World Example

When you run Playwright tests:

// Your test file: test.js
const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await browser.close();
})();

What happens when you run node test.js:

  1. Node.js runtime starts → Loads V8 engine, initializes event loop
  2. V8 parses your code → Converts JavaScript to machine instructions
  3. Node.js provides 'require' → Loads the Playwright module
  4. Event loop manages async operations → Browser launch, page navigation
  5. libuv handles I/O → Network requests, file system operations
  6. Process ends → Node.js cleans up and exits

Key Takeaway

Runtime environment = Everything needed to execute your code

Without Node.js runtime:

  • JavaScript would only run in browsers
  • No access to file system, network, or OS features
  • No way to build backend servers, CLI tools, or automation scripts

With Node.js runtime:

  • JavaScript can run anywhere
  • Full access to computer resources
  • Can build complete applications (frontend + backend)

The Node.js runtime is why tools like Playwright can control browsers, read files, make network requests, and automate complex workflows - all using JavaScript!

 

 

 

 

 

Comments

Popular posts from this blog

Why do we need Node.js as a pre-requisite before installing Playwright?

Await and Async

What is spec.ts?