JavaScript is a popular programming language used in both the browser and server-side applications. However, there are significant differences between how it works in the browser and in Node.js.
In a browser, the global object is window
, while in Node.js, it is global
. For example, to log the global object in a browser, we can use:
console.log(window);
To do the same in Node.js, we use:
console.log(global);
We can import modules in the browser using script tags with the type
attribute set to module
and the src
attribute set to the path of the module file. For example:
<script type="module" src="./module.js"></script>
We can then use the exported functions in our JavaScript code. For instance, we can import a sayHello
function from a module called module.js
and use it in our main JavaScript file as follows:
import { sayHello } from './module.js';
sayHello();
On the other hand, in Node.js, we use the require
or import
statement to import modules:
import { module } from './module.js';
The browser has a Document Object Model (DOM) that allows us to interact with HTML elements. For example, to change the text of an HTML element in the browser, we can use:
document.getElementById('elementId').innerHTML = 'New text';
However, in Node.js, there is no DOM, so we cannot access or manipulate HTML elements.
Node.js is mainly used for server-side applications, while the browser is used for websites. For example, we can create a simple server in Node.js using:
const http = require('http');
const server = http.createServer((req, res) => {
res.write('Hello World!');
res.end();
});
server.listen(3000);