Node.js is a powerful tool that allows you to run JavaScript code directly on your computer, outside of a web browser. This means you can use JavaScript to build all kinds of applications, not just websites. You will learn what Node.js is, how it works, and how to start building your own JavaScript programs for your computer or servers.
Node.js Environment
Node.js Environment
When you write JavaScript for a website, it runs inside your web browser. But what if you want to use JavaScript to build other things, like a program that runs on your computer, or a server that handles website requests?
This is where Node.js comes in. It is a special software that lets your computer understand and run JavaScript code without needing a browser. It extends JavaScript's abilities far beyond just making web pages interactive.
What is Node.js?
Node.js is a JavaScript runtime environment. It allows you to execute JavaScript code outside of a web browser, typically for building server-side applications, command-line tools, and desktop programs.
Server-Side JavaScript
Node.js lets you build powerful backend servers for websites and applications using JavaScript.
Fast Performance (V8)
It uses Google's V8 engine, the same one in Chrome, to execute your JavaScript code very quickly.
npm Package Manager
Node.js comes with npm, a huge library of reusable code packages created by other developers.
Command-Line Tools
You can create scripts and tools that run directly in your computer's terminal using Node.js.
What is Node.js?
What is Node.js?
Think of Node.js as a special program you install on your computer. Once installed, it gives your computer the ability to run JavaScript files. Before Node.js, JavaScript could only run inside web browsers.
Node.js uses the same JavaScript engine that Google Chrome uses, called V8. This engine is incredibly fast at turning your JavaScript code into instructions your computer can understand. This speed makes Node.js great for tasks that need to happen quickly, like handling many requests on a server.
1// Save this code in a file named 'hello.js'23// Use console.log just like in the browser4console.log('Hello from Node.js!');56// You can do math operations7let sum = 5 + 3;8console.log('The sum is:', sum);910// To run this file, open your terminal (command prompt)11// and type: node hello.js
Node.js is not a new programming language
Node.js does not introduce a new language. It simply provides an environment where you can use the JavaScript language outside of the browser. All your existing JavaScript knowledge still applies, but you gain new abilities like reading files or talking to databases.
How Node.js Works
How Node.js Works
Node.js is designed to be very efficient, especially when dealing with many tasks at once. It achieves this using something called an event loop and non-blocking I/O.
Imagine a busy restaurant where one waiter takes orders, passes them to the kitchen, and then immediately goes to the next table. They do not wait for the food to be cooked before taking another order. This is like Node.js: it starts a task (like reading a file) and moves on to the next task without waiting for the first one to finish. When the first task is done, Node.js gets a notification and handles the result.
1// This line runs first2console.log('Start of script');34// This line tells Node.js to wait 2 seconds, then run the function5// Node.js does not stop and wait here; it moves to the next line immediately6setTimeout(() => {7 console.log('This runs after 2 seconds (asynchronously)');8}, 2000);910// This line runs right after setTimeout starts, not after it finishes11console.log('End of script (before timeout finishes)');1213// Output will be:14// Start of script15// End of script (before timeout finishes)16// This runs after 2 seconds (asynchronously)
// Imagine this takes 5 seconds to finishfunction readFileBlocking() {// Code that makes the program waitconsole.log('File read blocking: Done');}console.log('Before blocking call');readFileBlocking();console.log('After blocking call'); // This waits 5 seconds
// This tells Node.js to read file and call function when donefunction readFileNonBlocking() {setTimeout(() => {console.log('File read non-blocking: Done');}, 5000);}console.log('Before non-blocking call');readFileNonBlocking();console.log('After non-blocking call'); // This runs immediately
Node.js vs. Browser JavaScript
Node.js vs. Browser JavaScript
While both Node.js and browser JavaScript use the same core language, they have different environments and capabilities. Browser JavaScript can interact with web page elements (like buttons and text), but it cannot access files on your computer.
Node.js, on the other hand, cannot directly interact with a web page's HTML or CSS. Instead, it can do things like read and write files, connect to databases, and handle network requests, making it perfect for server-side tasks and command-line tools.
// Accessing elements on a web pageconst button = document.getElementById('myButton');button.addEventListener('click', () => {alert('Button clicked!');});// Global object is 'window'console.log(window.location.href);// Cannot access local files// fs.readFile('mydata.txt', ...); // ❌ Error
// Reading and writing files on your computerconst fs = require('fs');fs.readFile('data.txt', 'utf8', (err, data) => {if (err) throw err;console.log('File content:', data);});// Global object is 'global'console.log(global.process.version);// Cannot access web page elements// document.getElementById('myButton'); // ❌ Error
// Accessing elements on a web pageconst button = document.getElementById('myButton');button.addEventListener('click', () => {alert('Button clicked!');});// Global object is 'window'console.log(window.location.href);// Cannot access local files// fs.readFile('mydata.txt', ...); // ❌ Error
// Reading and writing files on your computerconst fs = require('fs');fs.readFile('data.txt', 'utf8', (err, data) => {if (err) throw err;console.log('File content:', data);});// Global object is 'global'console.log(global.process.version);// Cannot access web page elements// document.getElementById('myButton'); // ❌ Error
Choose the right tool for the job
Use browser JavaScript for anything that runs directly inside a user's web browser, like interactive elements or animations. Use Node.js for tasks that run on a server or your local machine, such as building APIs, processing data, or creating command-line utilities.
Setting Up Your Node.js Project
Setting Up Your Node.js Project
To start building with Node.js, you usually create a new project folder. Inside this folder, you will use a tool called npm (Node Package Manager) to manage your project. npm helps you install useful libraries from other developers and keeps track of them.
The package.json file is like a blueprint for your Node.js project. It lists your project's name, version, and all the external code libraries (called 'packages') it uses.
Install Node.js
First, you need to install Node.js on your computer. Visit the official Node.js website (nodejs.org) and download the recommended installer for your operating system. This also installs npm.
1node -v // Check Node.js version2npm -v // Check npm version
Create a new project folder
Make a new folder for your project and navigate into it using your terminal.
1mkdir my-node-app2cd my-node-app
Initialize your project with npm
Run npm init to create a package.json file. You can press Enter for most questions, or use npm init -y to accept all defaults.
1npm init -y
Create your JavaScript file
Create a file, usually named index.js or app.js, where your main JavaScript code will live.
1// Create a file named 'index.js'2// Add some simple code to it34console.log('My Node.js app is running!');
Run your Node.js application
Execute your JavaScript file using the node command followed by the filename.
1node index.js
Always use package.json for dependencies
When you install external packages (like express or lodash), always make sure they are saved in your package.json file. This tells other developers what your project needs to run. If you forget to save them, others will not be able to easily set up your project.
Key Node.js Components
Key Node.js Components
| Component | What it is | Why it matters |
|---|---|---|
| V8 Engine | Google's open-source JavaScript engine | Executes JavaScript code very fast, making Node.js efficient. |
| Libuv | A C++ library for asynchronous I/O | Enables Node.js to handle many tasks without blocking, using the event loop. |
| npm | Node Package Manager | Manages external code packages (libraries) for your Node.js projects. |
| Core Modules | Built-in Node.js libraries (e.g., `fs`, `http`) | Provide essential functionalities like file system access, networking, and crypto. |
Test Your Knowledge
Test Your Knowledge
What is the primary purpose of Node.js?
Which JavaScript engine does Node.js use?
What is a key difference between Node.js and browser JavaScript?
What is npm primarily used for in a Node.js project?
Quick Reference
Quick Reference
- 1Node.js — a JavaScript runtime environment that executes JavaScript code outside a web browser.
- 2V8 Engine — the high-performance engine from Google Chrome that Node.js uses to run JavaScript code.
- 3Non-blocking I/O — Node.js can start a task and move on without waiting for it to finish, making it efficient for many concurrent operations.
- 4Event Loop — the core mechanism that allows Node.js to handle asynchronous operations efficiently.
- 5npm — the Node Package Manager, used for installing and managing external code libraries (packages) for your projects.
- 6
package.json— a file that describes your Node.js project and lists all its dependencies. - 7Server-side — Node.js is commonly used to build the backend (server) of web applications.
- 8Command-line tools — you can create scripts that run directly in your terminal using Node.js.
- 9Core Modules — Node.js provides built-in modules like
fs(file system) andhttp(networking) for common tasks. - 10JavaScript language — Node.js does not introduce a new language; it's still standard JavaScript, but with different available APIs.
Node.js Modules
Learn how to organize your code into reusable modules and use built-in Node.js modules.
Asynchronous JavaScript
Dive deeper into callbacks, Promises, and async/await for handling non-blocking operations.
Express.js Framework
Discover Express.js, a popular framework for building web servers and APIs with Node.js.
Node.js CLI Tools
Explore how to create your own command-line interface tools using Node.js.
You now understand the Node.js Environment!
You have learned that Node.js allows JavaScript to run outside the browser, how its V8 engine and event loop work, and the role of npm. This knowledge is crucial for building powerful backend applications and command-line tools with JavaScript.
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.