Understanding Node.js and Express: A Comprehensive Guide
Introduction to Node.js
Node.js is a runtime environment that allows you to execute JavaScript code outside of a web browser. It’s built on the V8 JavaScript runtime and is designed to be efficient and scalable. In this guide, we’ll explore Node.js, its installation process on Windows, and fundamental concepts associated with it.
Installation of Node.js on Windows
Download Node.js: Visit the official Node.js website and download the latest version for Windows.
Installation Process:
- Run the installer executable.
- Follow the installation wizard, accepting the default settings.
Verification:
- Open a command prompt and type
node -v
to check if Node.js is installed. - Type
npm -v
to check the Node Package Manager (npm) version.
Basics of Node.js
process.argv
in Node.js
process.argv
is an array containing the command-line arguments passed to the Node.js process. It allows you to access and manipulate these arguments in your scripts.
Example:
// filename: processArgs.js
console.log(process.argv);
Run using: node processArgs.js arg1 arg2
module.exports
and require
In Node.js, modules are reusable pieces of code. module.exports
is used to expose functionality from a module, and require
is used to import that functionality in another module.
Example:
// filename: mathOperations.js
module.exports = {
add: (a, b) => a + b,
subtract: (a, b) => a — b
};
In another file:
// filename: main.js
const math = require(‘./mathOperations’);
console.log(math.add(5, 3));
Node Package Manager (npm)
npm is the default package manager for Node.js. It allows you to install and manage third-party packages and libraries for your projects.
npm install packageName
: Installs a package locally.npm install -g packageName
: Installs a package globally.npm init
: Initializes a newpackage.json
file.
Node.js Commands
node filename.js
: Runs a Node.js script.npm start
: Executes thestart
script defined inpackage.json
.
Understanding node_modules
When you install packages using npm, they are stored in the node_modules
directory. This directory contains all the dependencies your project relies on.
package-lock.json
and package.json
package.json
: A manifest file that includes metadata about the project and its dependencies.package-lock.json
: Locks down the version of each package's dependencies, ensuring consistency across different installations.
import
vs require
import
and require
are used to include external modules in your code. import
is part of ECMAScript modules, while require
is the CommonJS way of including modules.
Example (using import
):
// ECMAScript module syntax
import { add } from ‘./mathOperations’;
console.log(add(5, 3));
Example (using require
):
// CommonJS syntax
const { add } = require(‘./mathOperations’);
console.log(add(5, 3));
Introduction to Express.js
Express.js is a web application framework for Node.js. It simplifies the process of building robust web applications by providing a set of features and tools.
Installation of Express.js
Installation via npm: Open a terminal and run the following command:
npm install express
Usage in Code:
const express = require(‘express’);
const app = express();
Express.js Basic Concepts and Examples
Listening on Port 8080
const express = require(‘express’);
const app = express();
app.listen(8080, () => {
console.log(‘Server is running on port 8080’);
});
app.use()
app.use()
is used to mount middleware functions in the application's request processing pipeline.
Example:
app.use(express.json()); // Parse incoming JSON requests
app.use(express.static(‘public’)); // Serve static files from the ‘public’ directory
res.send()
res.send()
is used to send a response to the client.
Example:
app.get(‘/’, (req, res) => {
res.send(‘Hello, World!’);
});
app.get()
and app.post()
app.get()
and app.post()
are used to define routes for handling GET and POST requests, respectively.
Example:
app.get(‘/about’, (req, res) => {
res.send(‘About Us’);
});
app.post(‘/submit’, (req, res) => {
res.send(‘Form submitted successfully’);
});
Express.js Routing
Routing refers to how an application’s endpoints (URIs) respond to client requests. Express.js provides a clean and flexible way to handle routing.
Example:
// Define routes in separate files for better organization
const indexRoutes = require(‘./routes/index’);
const userRoutes = require(‘./routes/user’);
// Use the routes in the main app
app.use(‘/’, indexRoutes);
app.use(‘/user’, userRoutes);
Path Parameters in Express.js
Path parameters are used to capture values from the URL.
Example:
app.get(‘/user/:id’, (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
Query Strings in Express.js
Query strings allow you to pass data to the server through the URL.
Example:
app.get(‘/search’, (req, res) => {
const query = req.query.q;
res.send(`Search Query: ${query}`);
});
Conclusion
Congratulations! You’ve journeyed through the realms of Node.js and Express.js, equipped with the knowledge to embark on your web development adventures. Whether you’re a beginner or an experienced developer, this guide has laid the foundation for building scalable and efficient applications. Now, go forth and code with confidence!