0
0
Node.jsframework~5 mins

How Node.js differs from browser JavaScript in Node.js

Choose your learning style9 modes available
Introduction

Node.js lets you run JavaScript outside the browser, so you can build things like servers and tools. Browser JavaScript runs inside web pages to make them interactive.

When you want to build a web server that handles requests.
When you need to read or write files on your computer using JavaScript.
When you want to create command-line tools with JavaScript.
When you want to use JavaScript to connect to databases.
When you want to run JavaScript code without opening a web browser.
Syntax
Node.js
// Node.js example
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

// Browser JavaScript example
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data));

Node.js uses modules like fs to access files, which browsers cannot do for security reasons.

Browser JavaScript uses fetch to get data from the internet, which Node.js can also do but often uses other libraries.

Examples
This code saves text to a file on your computer using Node.js.
Node.js
// Node.js: Accessing the file system
const fs = require('fs');
fs.writeFile('hello.txt', 'Hello from Node.js!', err => {
  if (err) throw err;
  console.log('File saved!');
});
This code changes the text inside an <h1> tag on a web page.
Node.js
// Browser JavaScript: Changing page content
const heading = document.querySelector('h1');
heading.textContent = 'Hello from the browser!';
Node.js has a global object with info about the environment, unlike browsers.
Node.js
// Node.js: Using global variables
console.log(global.process.version);
Browser JavaScript has a window object to access browser info.
Node.js
// Browser JavaScript: Using window object
console.log(window.navigator.userAgent);
Sample Program

This Node.js program reads a file named example.txt and prints its content. Browsers cannot do this because they don't have file system access.

Node.js
import fs from 'fs';

// Read a file in Node.js
fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  console.log('File content:', data);
});
OutputSuccess
Important Notes

Node.js can do many things browsers cannot, like reading files or running servers.

Browser JavaScript focuses on interacting with web pages and user actions.

Some JavaScript features work the same in both, but environment objects like window and global differ.

Summary

Node.js runs JavaScript outside the browser and can access files and servers.

Browser JavaScript runs inside web pages and controls what users see and do.

They share the JavaScript language but have different tools and objects to work with.