Comprehensive Guide to Node.js: Features, Modules, and NPM
Aman
Technical Writer & Educator
What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment.
It allows JavaScript to run outside the browser, especially on the server side.
Node.js uses Google's V8 JavaScript engine to execute JavaScript code.
With Node.js, JavaScript can be used for both:
- Client-side development
- Server-side development
Features of Node.js
1. Event-Driven
Node.js uses an event-driven architecture. It can respond to events such as requests, file operations, and user actions.
2. Non-Blocking
Node.js does not wait for one operation to finish before handling other tasks.
3. Asynchronous I/O
Node.js can perform input/output operations asynchronously, allowing other tasks to continue while waiting for operations such as file or database access.
Uses of Node.js
Node.js is commonly used for:
- Web servers
- REST APIs
- Real-time applications
- Chat applications
- Backend development
- Command-line tools
Installing Node.js
Download and install Node.js from the official Node.js website.
After installation, check the version:
Check NPM:
HTTP Module
The built-in http module can be used to create an HTTP server.
It does not require an additional package.
Save the file as:
Run it using:
HTTP Response Methods
writeHead()
writeHead() sends the HTTP status code and response headers.
200 means the request was successful.
Content-Type: text/plain tells the browser that the response contains plain text.
write()
write() sends data to the response body.
end()
end() tells Node.js that the response has been completed.
You should normally call end() after writing the response.
Port Environment Variable
The port can be provided using an environment variable.
A common approach is:
Here:
process.env.PORTis used if available.3000is used as the default port.
Node.js Routing
Node.js can check the requested URL using:
Example:
Here, req.url tells us which URL the client requested.
Nodemon
Normally, when you change your Node.js code, you need to restart the application manually.
Nodemon automatically restarts the application when files change.
Install Nodemon
Run the Application
Now the application automatically restarts when you modify the file.
Environment Variables with dotenv
Environment variables are useful for storing configuration values.
Create a .env file in the project root:
Install the dotenv package:
Load the .env file:
Access an environment variable:
Output:
Console Output in Node.js
Node.js provides the console object for displaying information in the terminal.
Format Specifiers
%s
Used for strings.
%d
Used for numbers.
%i
Used for integers.
%o
Used for objects.
Console Methods
console.log()
Used to print information.
console.clear()
Clears the console.
Import and Export in Node.js
Node.js supports the CommonJS module system using require() and module.exports.
Exporting a Value
Create a file named:
Import it into another file:
Output:
Exporting Multiple Values
You can export values as properties.
Import them:
Output:
NPM
NPM stands for Node Package Manager.
It is used to:
- Install packages
- Remove packages
- Update packages
- Manage project dependencies
- Run project scripts
Installing a Package
Example:
The package will be added to the project's dependencies.
Updating Packages
To update installed packages:
Uninstalling Packages
Remove a local package:
Remove a globally installed package:
package.json
package.json contains information about a Node.js project and its packages.
A basic package.json may look like:
Important Properties
name
The name of the application.
version
The current version of the application.
description
A short description of the application.
main
The main entry point of the application.
scripts
Defines commands that can be run using NPM.
dependencies
Contains packages required by the application at runtime.
devDependencies
Contains packages mainly required during development.
NPM Scripts
Example:
Run the script using:
For the start script, you can also use:
Installing a Development Dependency
Use:
Example:
The package will be added to devDependencies.
OS Module
The built-in os module provides information about the operating system.
Import it:
Common Methods
os.arch()
Returns the CPU architecture.
Example output:
os.cpus()
Returns information about the system CPUs.
os.freemem()
Returns the amount of free system memory in bytes.
os.homedir()
Returns the current user's home directory.
os.networkInterfaces()
Returns information about the available network interfaces.
os.platform()
Returns the operating system platform.
os.totalmem()
Returns the total system memory in bytes.
os.type()
Returns the operating system name.
os.uptime()
Returns the number of seconds the system has been running since the last restart.
os.userInfo()
Returns information about the current user.
Path Module
The built-in path module provides utilities for working with file and directory paths.
Import it:
Common Methods
path.basename()
Returns the last part of a path.
Output:
path.dirname()
Returns the directory part of a path.
Output:
path.extname()
Returns the extension of a file.
Output:
path.join()
Joins multiple path parts together.
File System Module
The built-in fs module is used to work with files and directories.
Import it:
fs.readFile()
Reads the content of a file asynchronously.
fs.writeFile()
Writes data to a file.
If the file does not exist, it can create the file.
fs.appendFile()
Adds new content to the end of a file.
fs.unlink()
Deletes a file.
fs.rename()
Renames a file or directory.
fs.mkdir()
Creates a new directory.
fs.rmdir()
Removes a directory.
Note: For newer Node.js code, fs.rm() is generally preferred for removing directories because fs.rmdir() is deprecated in current Node.js versions.