In a browser environment, JavaScript is used to manipulate the Document Object Model (DOM), handle user events, and make asynchronous requests to servers using technologies like AJAX. The global object in the browser is window
, which provides access to various browser - specific features such as document
, location
, and navigator
.
Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows developers to run JavaScript code outside of the browser. In Node.js, the global object is global
, and it provides a different set of features compared to the browser’s window
object. Node.js has a built - in module system, which allows you to organize your code into reusable modules.
To use JavaScript in the browser, you typically include a <script>
tag in your HTML file. You can either write your JavaScript code directly inside the <script>
tag or reference an external JavaScript file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF - 8">
</head>
<body>
<button id="myButton">Click me</button>
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', function () {
alert('Button clicked!');
});
</script>
</body>
</html>
To use Node.js, you first need to have it installed on your machine. You can create a JavaScript file (e.g., app.js
) and run it using the node
command in the terminal.
// app.js
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content - Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
To run the above code, open your terminal and navigate to the directory containing app.js
, then run the command node app.js
.
const newElement = document.createElement('p');
newElement.textContent = 'This is a new paragraph.';
document.body.appendChild(newElement);
fs
module to work with the file system. For example, reading a file:const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
EventEmitter
class, which is useful for handling asynchronous events in a modular way.const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('message', (message) => {
console.log(`Received message: ${message}`);
});
myEmitter.emit('message', 'Hello, Node.js!');
JavaScript in the browser and Node.js have different use cases and environments. While browser - based JavaScript is focused on enhancing the user experience by interacting with the DOM and handling user events, Node.js is designed for server - side development, file system operations, and building scalable network applications. Understanding the key differences between the two will help you make better decisions when choosing the appropriate technology for your projects.