JavaScript can be used for both front-end and back-end development with Node.js, allowing developers to form productive and cooperative full-stack teams. Node.js developers are in high demand, as evidenced by the sharp rise in job postings in recent years. Explore the fundamentals with this Node JS developer tutorial prepared for beginners. Get started with our Node JS course syllabus.
Node JS Introduction
Building scalable and effective network applications is made possible by Node.js, a runtime environment that enables JavaScript code to be executed outside of a web browser, mostly on the server-side. Node JS for beginners tutorial covers from fundamentals to beginner projects.
- JavaScript: The programming language that you probably recognize from web browsers is called JavaScript.
- Runtime Environment: Node.js allows your server or PC to run JavaScript by embedding the V8 JavaScript engine, the same one used in Chrome, into a C++ program.
- Server-Side: Web applications’ backends (which manage databases, APIs, etc.) were constructed using languages like Python, Java, or Ruby. All of that is possible using JavaScript and Node.js.
- Scalable and Effective: Node.js’s event-driven, non-blocking architecture allows it to manage numerous connections at once without using excessive amounts of resources.
- Network Applications: Node.js is especially well-suited for creating web servers, APIs, and real-time applications, though it may be used to create other things as well.
Recommended: Node JS Course Online Program.
Use Cases of Node JS
Because of its great versatility, Node.js may be used to create a variety of apps, such as:
- Web Servers and APIs: Building scalable and reliable RESTful APIs and web apps is made simple by frameworks like Express.js and NestJS.
- Real-time Applications: As it is event-driven and non-blocking, it is perfect for applications like online games, chat programs, and teamwork tools that need continuous two-way communication.
- Command-Line Tools: Node.js allows you to create robust scripts and command-line tools.
- Desktop Applications: With frameworks like Electron, you can use web technologies like HTML, CSS, and JavaScript to create cross-platform desktop applications.
- Microservices: Because Node.js is lightweight, it’s an excellent choice for creating separate microservices within a more extensive distributed system.
- Internet of Things (IoT) Applications: Node.js can be used to create apps that communicate with and control IoT devices.
Suggested: MEAN Stack course in Chennai.
Installation of Node JS and npm
Depending on your operating system, take the following actions to install Node.js and npm:
Windows:
Using the Installer
- Visit https://nodejs.org/en/download/, the official Node.js download website.
- Get the LTS (Long-Term Support) version of the Windows Installer (.msi).
- Launch the.msi file that you downloaded.
- Follow the Node.js Setup Wizard’s on-screen directions.
- The license agreement must be accepted before clicking “Next.”
- Unless you have a compelling need to modify the installation location, leave it at its default setting and click “Next.”
- Make sure that npm is chosen for installation in the “Custom Setup” section (it is by default). Installing additional supplementary tools is another possibility. Press “Next.”
- Press “Install” to start the installation process. An administrator permission window may appear; select “Yes.”
- After the installation process is finished, select “Finish.”
- To make sure the environment variables are updated, it is advised that you restart your computer.
macOS:
Using the Installer:
- Visit https://nodejs.org/en/download/, the official Node.js download website.
- Get the LTS version of the macOS Installer (.pkg).
- Launch the.pkg file that was downloaded.
- Observe the installation wizard’s instructions.
Linux:
Using your Distribution’s Package Manager: Debian/Ubuntu:
sudo apt update
sudo apt install nodejs npm
Fedora/RHEL/CentOS:
sudo dnf update
sudo dnf install nodejs npm
Verifying Installation:
To confirm the installation and check the versions, run the following commands in your terminal (macOS/Linux) or command prompt (Windows) after installing Node.js and npm:
node -v
npm -v
The installed versions of npm and Node.js should be printed by these commands, respectively.
Suggested: MERN Stack Course in Chennai.
Node JS Core Modules
The built-in libraries that are included with Node.js and offer necessary features without requiring an external installation are called Node.js modules. They function similarly to the fundamental building elements that you may easily incorporate into your Node.js apps.
File System and Streams:
- fs (File System): This module lets you work with your computer’s file system. You can check for the existence of files, create and delete folders, read and write files, and more.
const fs = require(‘node:fs’);
fs.readFile(‘my-file.txt’, ‘utf8’, (err, data) => {
if (err) throw err;
console.log(data);
});
- stream: To work with streaming data, this module offers an abstract interface. Processing music and video, managing network requests, and reading big files are a few examples.
const fs = require(‘node:fs’);
const readableStream = fs.createReadStream(‘large-file.txt’, { highWaterMark: 16384 });
readableStream.on(‘data’, (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
readableStream.on(‘end’, () => {
console.log(‘Finished reading the file.’);
});
Networking:
- http: This module offers features for setting up and controlling HTTP clients and servers. It serves as the foundation for creating HTTP requests and web applications.
const http = require(‘node:http’);
const server = http.createServer((req, res) => {
res.writeHead(200, { ‘Content-Type’: ‘text/plain’ });
res.end(‘Hello, World!’);
});
server.listen(3000, () => {
console.log(‘Server listening on port 3000’);
});
- https: Using SSL/TLS encryption, this module offers features that are comparable to those of the http module but for secure HTTP (HTTPS) communications.
- net: Useful for creating unique network protocols, it is a lower-level module compared to http and https.
- dgram: This module facilitates connectionless network communication by supporting UDP (User Datagram Protocol) datagram sockets.
Paths and URLs:
- path: This module offers platform-independent tools for manipulating file and directory paths. It facilitates file name extraction, path string manipulation, path joining, and more.
const path = require(‘node:path’);
const filePath = ‘/users/node/myfile.txt’;
console.log(path.basename(filePath)); // Output: myfile.txt
console.log(path.dirname(filePath)); // Output: /users/node
console.log(path.join(‘/users’, ‘node’, ‘data.txt’)); // Output: /users/node/data.txt (or appropriate for the OS)
- url (Legacy): This module offers tools for parsing and formatting URLs, however it has been mostly replaced by the WHATWG URL API, which is accessible worldwide. With earlier codebases, it is still applicable.
- whatwg-url (Global): This offers a more contemporary and standardized method of working with URLs by implementing the WHATWG URL Standard. Because it’s accessible everywhere, you don’t need to specifically demand it.
Utilities and Data Handling:
- util: This module offers a number of utility functions, like formatting strings (util.format), examining objects (util.inspect), and working with promises, that are frequently useful for debugging and basic programming chores.
const util = require(‘node:util’);
console.log(util.format(‘Hello, %s!’, ‘Node.js’)); // Output: Hello, Node.js!
const obj = { a: 1, b: { c: 2 } };
console.log(util.inspect(obj, { depth: null })); // Output: { a: 1, b: { c: 2 } }
- buffer: This module offers a method for working with binary data. Node.js makes heavy use of buffers for file, network stream, and other operations.
- zlib: This module uses algorithms like Gzip and Deflate to give compression and decompression capabilities.
Processes and Operating System:
- process (Global): This global object gives you control over and information about the active Node.js process. Memory utilization, process ID, command-line arguments, environment variables, and more are all accessible.
console.log(`Process ID: ${process.pid}`);
console.log(`Current working directory: ${process.cwd()}`);
console.log(`Environment variable NODE_ENV: ${process.env.NODE_ENV}`);
- os: This module offers utility methods relating to the operating system, including retrieving data about the platform, network interfaces, CPU, and RAM.
Related Training: MongoDB training in Chennai.
NPM (Node Package Manager)
The essential toolbox for any Node.js developer is npm. It serves as the command-line interface and main hub for managing JavaScript packages, sometimes referred to as modules or dependencies. Finding, installing, upgrading, and sharing code is made easier by it.
What is npm?
- Package Manager: npm functions as a package management. Installing and managing reusable code packages that have been produced by others and made available to the community is made simple by it.
- Online Repository (npm Registry): The extensive online repository (registry) at https://www.npmjs.com/ is also referred to as npm. You may easily utilize the hundreds of thousands of open-source packages found in this registry for your Node.js projects.
- Command-Line Interface (CLI): To manage packages in your projects and connect with the registry, npm includes a robust command-line tool that you use in your terminal.
The package.json File:
The core of your Node.js project’s dependency management is the package.json file. The file is in JSON format and includes:
- name: The project’s name.
- version: Your project’s most recent iteration.
- description: Give a succinct overview of your project.
- main: Your application’s entry point, typically server.js or index.js.
- scripts: Scripts that define objects and can be executed using npm run.
- dependencies: A list of the packages, together with the versions or ranges of versions, that your application requires in order to function in production.
- devDependencies: A list of packages, together with their versions, that are required for development (such as testing and linting).
- repository: Details about the repository for your project (e.g., GitHub URL).
- author: Details about the author of the project.
- license: The license used to distribute your project.
By making it simple to manage and reuse code from the extensive JavaScript ecosystem, npm is a vital tool that expedites the process of developing Node.js apps.
Explore our web development training program in Chennai.
Node JS Asynchronous Programming
The core concept of asynchronous programming in Node.js enables your applications to be incredibly responsive and performant, particularly when handling I/O-bound processes like file system access, network requests, and database interactions.
Node.js uses an asynchronous, non-blocking method in place of waiting for these activities to finish, which would prevent other code from running.
Callbacks
This is the first and most used method. Usually, a callback function is passed as an argument to asynchronous functions.
An error object, if any, is typically passed as the first argument and the result as the second parameter or arguments when this callback is invoked after the asynchronous action is finished.
const fs = require(‘node:fs’);
fs.readFile(‘my-file.txt’, ‘utf8’, (err, data) => {
if (err) {
console.error(‘Error reading file:’, err);
return;
}
console.log(‘File content:’, data);
});
console.log(‘Reading file…’); // This line executes before the file is read
Callback Hell (Pyramid of Doom): One major disadvantage of callbacks is that layered asynchronous operations can result in extremely complex and challenging-to-manage code, which is commonly known as “callback hell.”
Promises:
To solve the callback problems, promises were built. An asynchronous operation’s ultimate result, whether successful or unsuccessful, is represented by a promise. There are three possible states for it:
- Pending: The first condition, which is neither accepted nor denied.
- Fulfilled (Resolved): The promise has value, and the operation was successfully finished.
- Rejected: The promise has a reason for failing, and the operation failed.
With promises, handling asynchronous code with.then() for success and.catch() for faults is made cleaner. They also help in the more elegant chaining of asynchronous operations.
const fs = require(‘node:fs’).promises;
fs.readFile(‘my-file.txt’, ‘utf8’)
.then(data => {
console.log(‘File content:’, data);
return ‘Processed data: ‘ + data.toUpperCase(); // You can chain promises
})
.then(processedData => {
console.log(processedData);
})
.catch(err => {
console.error(‘Error reading file:’, err);
});
console.log(‘Reading file…’); // This line still executes first
Async/Await: Async/await is syntactic sugar. It makes asynchronous code easier to read and write by giving it a mostly synchronous appearance and behavior.
- An implicit promise is always returned by an async function.
- We can use the await keyword inside of an async function. Until the anticipated promise settles (either resolves or rejects), it halts the async function’s execution.
const fs = require(‘node:fs’).promises;
async function readFileAndProcess() {
try {
const data = await fs.readFile(‘my-file.txt’, ‘utf8’);
console.log(‘File content:’, data);
const processedData = ‘Processed data: ‘ + data.toUpperCase();
console.log(processedData);
} catch (err) {
console.error(‘Error reading file:’, err);
}
}
readFileAndProcess();
console.log(‘Reading file…’);
Key Concepts to Understand:
- Non-Blocking I/O: The fundamental concept behind Node.js’s effective handling of concurrency is non-blocking input/output.
- Event Loop: The core of Node.js’s asynchronous architecture, the event loop is in charge of organizing and carrying out asynchronous operations.
- Callbacks: They are functions that are executed when asynchronous operations are finished and supplied as parameters.
- Promises: A more streamlined method of handling errors and results, promises are objects that reflect the final result of an asynchronous activity.
- Async/Await: Syntactic sugar for promises that gives the appearance of synchronous code in asynchronous programming.
You may produce a thorough and useful Node.js developer tutorial by going over these ideas in an organized way.
Recommended: AngularJS course in Chennai.
Node JS Beginner Projects
Here we develop Node JS basic projects using Express.js and Node.js:
Step 1: Basic HTTP Server:
// http-server.js
const http = require(‘node:http’);
const hostname = ‘127.0.0.1’;
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader(‘Content-Type’, ‘text/plain’);
res.end(‘Hello, World from Node.js!\n’);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Step 2: Reading a File Asynchronously:
// read-file-async.js
const fs = require(‘node:fs’);
fs.readFile(‘sample.txt’, ‘utf8’, (err, data) => {
if (err) {
console.error(‘Error reading the file:’, err);
return;
}
console.log(‘File content:\n’, data);
});
console.log(‘Reading the file…’);
Step 3: Writing to a File Asynchronously:
// write-file-async.js
const fs = require(‘node:fs’);
const content = ‘This is some content to write to the file.’;
fs.writeFile(‘output.txt’, content, ‘utf8’, err => {
if (err) {
console.error(‘Error writing to the file:’, err);
return;
}
console.log(‘Data has been written to output.txt’);
});
console.log(‘Writing to the file…’);
Step 4: Using the path Module:
// path-example.js
const path = require(‘node:path’);
const filePath = ‘/users/node/documents/my-file.txt’;
console.log(‘Base name:’, path.basename(filePath)); // Output: my-file.txt
console.log(‘Directory name:’, path.dirname(filePath)); // Output: /users/node/documents
console.log(‘File extension:’, path.extname(filePath)); // Output: .txt
console.log(‘Is absolute:’, path.isAbsolute(filePath)); // Output: true
console.log(‘Join paths:’, path.join(‘/users’, ‘node’, ‘data.txt’)); // Output: /users/node/data.txt (platform-specific)
console.log(‘Resolve paths:’, path.resolve(‘temp’, ‘file.txt’)); // Output: The absolute path to temp/file.txt
Step 5: Simple Event Emitter:
// event-emitter.js
const EventEmitter = require(‘node:events’);
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on(‘event’, (arg1, arg2) => {
console.log(‘Event occurred!’, arg1, arg2);
});
myEmitter.emit(‘event’, ‘first argument’, ‘second argument’);
Step 6: Using node-fetch (External Module – requires installation):
// fetch-example.js
import fetch from ‘node-fetch’;
async function fetchData() {
try {
const response = await fetch(‘https://jsonplaceholder.typicode.com/todos/1’);
const data = await response.json();
console.log(‘Fetched data:’, data);
} catch (error) {
console.error(‘Error fetching data:’, error);
}
}
fetchData();
The examples provided offer a foundation for comprehending a number of fundamental Node.js ideas. You’ll mix these ideas as you learn more to create increasingly intricate and potent applications.
Explore: All In-Demand Software Courses.
Conclusion
From the fundamentals of what Node.js is and how to set it up to using Express.js to create dynamic web applications and communicate with databases, we’ve covered a lot of territory in this Node JS developer tutorial. Gain expertise with our Node JS training in Chennai.