Getting Started with Node.js: A Beginner’s GuideNode.js is a powerful JavaScript runtime that lets you run JavaScript on the server. It’s built on Chrome’s V8 engine and uses an event-driven, non-blocking I/O model that makes it lightweight and efficient — especially suitable for data-intensive, real-time applications. This guide walks you through the essential concepts and practical steps to get started with Node.js, from installation to building a simple web app.
What is Node.js?
Node.js is a JavaScript runtime environment that executes JavaScript code outside a browser. It allows developers to use JavaScript for server-side scripting—running scripts server-side to produce dynamic web page content before the page is sent to the user’s web browser. Unlike traditional server environments that create a new thread for each request, Node.js operates on a single-threaded event loop with non-blocking I/O operations, which helps it handle many connections concurrently.
Why choose Node.js?
- Fast execution: Runs on V8, Google’s high-performance JavaScript engine.
- Non-blocking I/O: Efficient handling of concurrent operations.
- Single language across stack: JavaScript on both client and server.
- Large ecosystem: npm (Node Package Manager) hosts hundreds of thousands of packages.
- Real-time friendly: Great for chat apps, gaming servers, streaming, and collaborative tools.
Prerequisites
- Basic knowledge of JavaScript (variables, functions, callbacks, promises).
- Familiarity with the command line/terminal.
- A code editor (VS Code, Sublime Text, etc.).
If you’re new to JavaScript, consider reviewing ES6 features like arrow functions, let/const, template literals, and promises before proceeding.
Installing Node.js
-
Visit the official Node.js website and download the LTS (Long Term Support) version for your OS.
-
Alternatively, use a version manager:
- For macOS/Linux: nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash nvm install --lts nvm use --lts
- For Windows: nvm-windows or use the installer from nodejs.org.
- For macOS/Linux: nvm (Node Version Manager)
-
Verify installation:
node -v npm -v
Your First Node.js Script
Create a file named hello.js:
console.log('Hello, Node.js!');
Run it:
node hello.js
You should see “Hello, Node.js!” printed in the terminal.
Understanding Modules
Node.js uses CommonJS modules by default. Each file is a module with its own scope.
- Exporting:
// math.js function add(a, b) { return a + b; } module.exports = { add };
- Importing:
// index.js const { add } = require('./math'); console.log(add(2, 3)); // 5
Since Node.js now supports ES modules (with .mjs extension or “type”: “module” in package.json), you can also use import/export syntax:
// package.json // { "type": "module" } // math.mjs export function add(a, b) { return a + b; } // index.mjs import { add } from './math.mjs'; console.log(add(2, 3));
Working with npm
npm is Node’s package manager.
-
Initialize a project:
npm init -y
This creates a package.json with defaults.
-
Install a dependency:
npm install express
-
Install a development dependency:
npm install --save-dev nodemon
-
Useful scripts in package.json:
"scripts": { "start": "node index.js", "dev": "nodemon index.js" }
Building a Simple Web Server with Express
Express is the most popular web framework for Node.js.
-
Create a project folder, run npm init, and install Express:
npm init -y npm install express
-
Create index.js: “`javascript import express from ‘express’; // if using ES modules // const express = require(‘express’); // if using CommonJS
const app = express(); const PORT = process.env.PORT || 3000;
app.get(‘/’, (req, res) => { res.send(‘Hello from Express and Node.js!’); });
app.listen(PORT, () => { console.log(Server is running on http://localhost:${PORT}
); });
3. Start the server:
node index.js
Open http://localhost:3000 in a browser. --- ### Handling Asynchronous Code Node.js is asynchronous. Learn callbacks, promises, async/await. - Callback example: ```javascript const fs = require('fs'); fs.readFile('file.txt', 'utf8', (err, data) => { if (err) return console.error(err); console.log(data); });
- Promises and async/await: “`javascript const fsPromises = require(‘fs’).promises;
async function readFile() { try {
const data = await fsPromises.readFile('file.txt', 'utf8'); console.log(data);
} catch (err) {
console.error(err);
} } readFile();
--- ### Working with Databases Popular choices: MongoDB (NoSQL), PostgreSQL/MySQL (SQL). - MongoDB with mongoose:
npm install mongoose
Basic connection: ```javascript import mongoose from 'mongoose'; await mongoose.connect(process.env.MONGO_URI);
- PostgreSQL with pg:
npm install pg
Basic usage:
import { Pool } from 'pg'; const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const res = await pool.query('SELECT NOW()'); console.log(res.rows);
Environment Variables and Configuration
Never hard-code secrets. Use environment variables and .env files with dotenv in development.
npm install dotenv
Create .env:
PORT=3000 API_KEY=yourkey
Load in code:
import dotenv from 'dotenv'; dotenv.config(); console.log(process.env.PORT);
Error Handling and Logging
- Use try/catch with async/await.
- Centralize error handling in Express using middleware:
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });
- Use logging libraries (winston, pino) for structured logs and log levels.
Testing
- Unit testing: Jest, Mocha + Chai.
- End-to-end: Supertest for HTTP endpoints.
Example Jest test:
npm install --save-dev jest
package.json scripts:
"test": "jest"
Security Basics
- Validate and sanitize user input (express-validator, Joi).
- Use HTTPS in production.
- Set HTTP headers with helmet:
npm install helmet
. - Rate-limit requests to avoid abuse (express-rate-limit).
- Keep dependencies up to date (npm audit, Renovate/Dependabot).
Performance Tips
- Use clustering (node’s cluster module or PM2) to use multiple CPU cores.
- Avoid blocking the event loop—move CPU-intensive tasks to workers.
- Cache responses where appropriate (Redis).
- Use streaming for large payloads.
Deploying Node.js Apps
Common options:
- Platform-as-a-Service: Heroku, Render, Fly.io.
- Containers: Docker + Kubernetes or cloud run.
- VPS: DigitalOcean, Linode, AWS EC2.
- Serverless: AWS Lambda, Cloudflare Workers (with wrappers).
Basic Dockerfile:
FROM node:18-alpine WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . CMD ["node", "index.js"]
Helpful Tools & Resources
- Node.js official docs: nodejs.org
- npm registry: npmjs.com
- Tutorials: freeCodeCamp, MDN Web Docs
- Debugging: node –inspect, Chrome DevTools, VS Code debugger
- Package managers: npm, yarn, pnpm
Next Steps / Learning Path
- Learn core Node modules: fs, http, stream, crypto, path.
- Build small projects: CLI tools, REST API, real-time chat with Socket.io.
- Study Express middleware, routing, and authentication (JWT, OAuth).
- Practice testing and CI/CD pipelines.
- Explore TypeScript for better type safety in larger projects.
Node.js lets you build fast, scalable server-side applications using JavaScript. Start small, focus on understanding asynchronous patterns, and gradually incorporate frameworks, databases, testing, and deployment. With steady practice you’ll be productive quickly and able to build real-world applications.
Leave a Reply