Node.js Tutorial

Learn to build scalable backend services using Node.js and JavaScript.

🚀 Start Tutorial

1. Environment Setup

Install Node.js


npm install -g create-react-app
// Windows - use nvm install 16 from https://unpkg.com
// MacOS - brew install node
// Linux - sudo apt install node

                    

Verify Installation


node -v
npm -v

                    

2. Hello, World!

Basic HTTP Server


const http = require('http');
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello from Node.js!\n');
});

server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

                    

3. Express Framework

Create Express App


npm init -y
npm install express

                    

Basic Routes


const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`);
});

                    

4. Building an API

Create JSON Endpoint


app.get('/api/users', (req, res) => {
  res.json([
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' }
  ]);
});

                    

Middleware


app.use(express.json());

app.post('/api/users', (req, res) => {
  const user = req.body;
  console.log('New user:', user);
  res.status(201).json({ message: 'User created' });
});

                    

5. RESTful Services

CRUD Endpoints


app.get('/products/:id', (req, res) => {
  const productId = req.params.id;
  res.json({ id: productId, name: 'Sample Product' });
});

                    

Error Handling


app.use((err, req, res, next) => {
  console.error('Error:', err.message);
  res.status(500).json({ error: 'Something went wrong' });
});

                    

6. Final Thoughts

This basic example covers the fundamentals of building server-side applications with Node.js. Expand this with: