Table of Contents
What is Node.js?
Node.js is a powerful JavaScript runtime built on Chrome's V8 JavaScript engine that allows you to run JavaScript on the server side. Unlike traditional JavaScript that runs only in browsers, Node.js enables you to build scalable network applications, web servers, and command-line tools using JavaScript.
Key Features of Node.js
- Asynchronous and Event-Driven: Node.js uses non-blocking I/O operations
- Single-Threaded: Uses a single thread with event looping
- Cross-Platform: Runs on Windows, macOS, and Linux
- Fast Execution: Built on Google's V8 engine
- Large Ecosystem: Access to npm (Node Package Manager)
Installing Node.js
Download Node.js from the official website (nodejs.org) and follow the installation instructions for your operating system.
# Check if Node.js is installed
node --version
# Check npm version
npm --version
Your First Node.js Program
Create a file called hello.js
:
// hello.js
console.log("Hello, Node.js!");
console.log("Welcome to server-side JavaScript!");
// Display current date and time
const now = new Date();
console.log("Current time:", now.toLocaleString());
Run the program:
node hello.js
Understanding the Global Object
In Node.js, the global object provides access to global variables and functions:
// Global variables in Node.js
console.log("Current directory:", __dirname);
console.log("Current file:", __filename);
console.log("Process ID:", process.pid);
console.log("Node.js version:", process.version);
Exercise
Create a Node.js script that:
- Displays your name and the current date
- Shows the Node.js version
- Prints the current working directory
What's Next?
In the next lesson, we'll explore Node.js modules and learn how to organize code using the module system.