Back to Blog
Learning

🟢 Introduction to Node.js: Bringing JavaScript to the Server

Oct 10, 2024
13 min read
🟢 Introduction to Node.js: Bringing JavaScript to the Server

🟢 Introduction to Node.js: Bringing JavaScript to the Server

For years, JavaScript lived only in the browser. You could make websites interactive, handle clicks, and manipulate the DOM. But that's where it stopped.

Then Node.js came along and changed everything.

Node.js lets you run JavaScript on the server. Suddenly, JavaScript developers could build entire applications—frontend AND backend—using the same language.

What is Node.js?

Think of Node.js like this:

  • ▹Browser JavaScript = JavaScript that runs in Chrome, Firefox, etc.
  • ▹Node.js = JavaScript that runs on your computer/server

It's the same JavaScript language, but with superpowers:

  • ▹Access to your file system
  • ▹Ability to create servers
  • ▹Can run databases
  • ▹Can handle HTTP requests
  • ▹Works with APIs

Why Node.js?

Before Node.js:

  • ▹Frontend: JavaScript
  • ▹Backend: Python, PHP, Java, Ruby, etc.
  • ▹Different languages = More to learn

With Node.js:

  • ▹Frontend: JavaScript
  • ▹Backend: JavaScript
  • ▹Same language = Less to learn!

Installing Node.js

Step 1: Download

Go to nodejs.org and download the LTS (Long Term Support) version.

Step 2: Verify Installation

node --version # Should show something like: v20.10.0 npm --version # Should show something like: 10.2.3

If both commands work, you're ready!

What is npm?

npm (Node Package Manager) comes with Node.js. It's like an app store for JavaScript code:

  • ▹Install packages = npm install package-name
  • ▹Use other people's code = Save time!
  • ▹Share your code = Publish packages

Your First Node.js Program

Create a file called hello.js:

console.log('Hello from Node.js!');

Run it:

node hello.js # Output: Hello from Node.js!

Congratulations! You just ran JavaScript outside the browser!

Understanding Modules

Node.js uses modules to organize code. Think of modules like separate files that can share code.

Creating a Module

Create math.js:

// Export functions function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } // Make functions available module.exports = { add, subtract };

Using a Module

Create app.js:

// Import the module const math = require('./math.js'); // Use it console.log(math.add(5, 3)); // 8 console.log(math.subtract(10, 4)); // 6

ES6 Modules (Modern Way)

You can also use modern ES6 syntax:

// math.js export function add(a, b) { return a + b; } // app.js import { add } from './math.js'; console.log(add(5, 3)); // 8

(Note: You need "type": "module" in package.json for ES6 modules)

Working with the File System

Node.js can read and write files:

Reading a File

const fs = require('fs'); // Read file fs.readFile('data.txt', 'utf8', (err, data) => { if (err) { console.error('Error:', err); return; } console.log(data); });

Writing a File

const fs = require('fs'); // Write file fs.writeFile('output.txt', 'Hello, Node.js!', (err) => { if (err) { console.error('Error:', err); return; } console.log('File written!'); });

Using Promises (Modern Way)

const fs = require('fs').promises; async function readFile() { try { const data = await fs.readFile('data.txt', 'utf8'); console.log(data); } catch (err) { console.error('Error:', err); } } readFile();

Creating Your First Server

This is where Node.js gets exciting!

Basic HTTP Server

Create server.js:

const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<h1>Hello from Node.js Server!</h1>'); }); server.listen(3000, () => { console.log('Server running on http://localhost:3000'); });

Run it:

node server.js

Visit http://localhost:3000 in your browser. You should see your message!

Handling Different Routes

const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<h1>Home Page</h1>'); } else if (req.url === '/about') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<h1>About Page</h1>'); } else { res.writeHead(404, { 'Content-Type': 'text/html' }); res.end('<h1>404 Not Found</h1>'); } }); server.listen(3000, () => { console.log('Server running on http://localhost:3000'); });

Using Express.js (Easier Way)

Building servers with plain Node.js works, but Express.js makes it much easier.

Installing Express

npm init -y npm install express

Creating an Express Server

Create app.js:

const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('<h1>Hello from Express!</h1>'); }); app.get('/about', (req, res) => { res.send('<h1>About Page</h1>'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });

Much cleaner! Express handles a lot of the complexity for you.

Understanding npm

package.json

When you run npm init, it creates a package.json file:

{ "name": "my-app", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "node app.js" }, "dependencies": { "express": "^4.18.2" } }

Installing Packages

# Install a package npm install express # Install as dev dependency npm install nodemon --save-dev # Install multiple packages npm install express cors dotenv

Scripts

Define scripts in package.json:

{ "scripts": { "start": "node app.js", "dev": "nodemon app.js", "test": "echo \"Error: no test specified\" && exit 1" } }

Run scripts:

npm start npm run dev

Common Node.js Concepts

Callbacks

Node.js uses callbacks for asynchronous operations:

const fs = require('fs'); fs.readFile('file.txt', 'utf8', (err, data) => { if (err) { console.error('Error:', err); return; } console.log(data); });

Promises

Modern way to handle async operations:

const fs = require('fs').promises; fs.readFile('file.txt', 'utf8') .then(data => console.log(data)) .catch(err => console.error('Error:', err));

Async/Await

Cleanest way to handle async:

const fs = require('fs').promises; async function readFile() { try { const data = await fs.readFile('file.txt', 'utf8'); console.log(data); } catch (err) { console.error('Error:', err); } } readFile();

Building a Simple API

Let's build a basic REST API:

const express = require('express'); const app = express(); // Middleware to parse JSON app.use(express.json()); // In-memory data store let users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ]; // GET all users app.get('/users', (req, res) => { res.json(users); }); // GET user by ID app.get('/users/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) { return res.status(404).json({ error: 'User not found' }); } res.json(user); }); // POST create user app.post('/users', (req, res) => { const newUser = { id: users.length + 1, name: req.body.name }; users.push(newUser); res.status(201).json(newUser); }); app.listen(3000, () => { console.log('API running on http://localhost:3000'); });

Environment Variables

Never hardcode secrets! Use environment variables:

Install dotenv

npm install dotenv

Create .env file

PORT=3000
DB_URL=mongodb://localhost:27017/myapp
SECRET_KEY=your-secret-key

Use in code

require('dotenv').config(); const port = process.env.PORT || 3000; const dbUrl = process.env.DB_URL; app.listen(port, () => { console.log(`Server running on port ${port}`); });

Important: Add .env to .gitignore!

Common Mistakes to Avoid

1. Blocking the Event Loop

// ❌ Bad - Blocks the server const data = fs.readFileSync('large-file.txt'); // ✅ Good - Non-blocking fs.readFile('large-file.txt', (err, data) => { // Handle data });

2. Not Handling Errors

// ❌ Bad fs.readFile('file.txt', (err, data) => { console.log(data); }); // ✅ Good fs.readFile('file.txt', (err, data) => { if (err) { console.error('Error:', err); return; } console.log(data); });

3. Forgetting to Install Dependencies

Always run npm install after cloning a project!

Your Learning Path

Week 1: Basics

  • ▹✅ Install Node.js
  • ▹✅ Run your first script
  • ▹✅ Understand modules
  • ▹✅ Work with files

Week 2: Servers

  • ▹✅ Create HTTP server
  • ▹✅ Install Express
  • ▹✅ Build simple API
  • ▹✅ Handle routes

Week 3: Advanced

  • ▹✅ Connect to database
  • ▹✅ Handle errors
  • ▹✅ Use middleware
  • ▹✅ Deploy your app

Week 4: Projects

  • ▹✅ Build REST API
  • ▹✅ Create full-stack app
  • ▹✅ Use environment variables
  • ▹✅ Deploy to production

Project Ideas

  1. ▹File Organizer - Organize files in folders
  2. ▹Simple API - Create REST endpoints
  3. ▹Web Scraper - Scrape website data
  4. ▹Chat Server - Real-time chat with WebSockets
  5. ▹Blog API - CRUD operations for blog posts

The Bottom Line

Node.js lets you:

  • ▹Run JavaScript on the server
  • ▹Build APIs and servers
  • ▹Work with files and databases
  • ▹Create full-stack apps with one language

Start with simple scripts. Build a server. Create an API. Before you know it, you'll be building complex applications!

Remember: Every Node.js expert started with console.log('Hello, Node.js!'). You've got this! 🚀

Now go create your first Node.js server and start building!

Back to BlogHome