Introduction to Node.js
A Beginner's Guide to Node.js
This article provides a comprehensive introduction to Node.js, covering its basics, installation, usage, and key differences from browser JavaScript.
Node.js Basics
Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that executes JavaScript code outside a web browser. It uses an event-driven, non-blocking I/O model, making it lightweight and efficient.
Node.js Information
Node.js is primarily used for building scalable network applications. It's popular for APIs, real-time applications, and microservices. Its package manager, npm (Node Package Manager), provides access to a vast ecosystem of modules.
Download and Installation
Download Node.js from the official website. The installer will guide you through the process. Make sure to select the correct installer for your operating system.
Path Variable Setup
Adding Node.js to your system's PATH environment variable allows you to run Node.js commands from any directory in your command prompt or terminal.
Running Node.js exe
After installation, you can run the Node.js executable directly from the installation directory. However, adding it to the PATH is recommended for easier access.
Using cmd
Once the PATH is set up, you can open your command prompt or terminal and type node -v
to verify the installation. This command will display the installed Node.js version.
REPL Terminal
REPL (Read-Eval-Print Loop) is an interactive environment provided by Node.js for experimenting with JavaScript code. You can access it by simply typing node
in your terminal.
Examples
> console.log("Hello from REPL!");
Hello from REPL!
> let x = 10;
undefined
> x + 5;
15
Running First Node.js Code
Create a file (e.g., hello.js
) with the following code:
console.log("Hello, world from Node.js!");
Run this code from your terminal using node hello.js
. The output will be displayed in the console.
Node.js Examples
Global Variables
In Node.js, some variables are globally accessible. global
is a global object. __dirname
gives the current directory. __filename
gives the current file name.
console.log(__dirname);
console.log(__filename);
Differences between Browser JavaScript and Node.js
Browser JavaScript runs in a web browser environment, while Node.js runs on a server. Browser JavaScript has access to the browser's APIs (DOM, etc.), while Node.js has access to server-side APIs (e.g., file system access). Node.js uses a different event loop model compared to most browsers.
Summary
- Node.js is a JavaScript runtime for server-side development.
- It uses an event-driven, non-blocking I/O model.
- It is known for its lightweight and efficient nature.
- The Node Package Manager (npm) provides access to a large community of modules.
- Node.js has global variables like
global
,__dirname
, and__filename
. - It is different from browser JavaScript in its execution environment and API access.