Toggle theme

Node.js Snippets

Server-side JavaScript with Node.js

Express Server

javascript

Basic Express.js server setup

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

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Routes
app.get('/', (req, res) => {
  res.json({ message: 'Welcome to the API' });
});

app.post('/api/users', async (req, res) => {
  try {
    const user = await User.create(req.body);
    res.status(201).json(user);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: 'Something broke!' });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

File System Operations

javascript

Async file operations with promises

const fs = require('fs').promises;
const path = require('path');

async function processFiles(directory) {
  try {
    // Read directory
    const files = await fs.readdir(directory);
    
    // Process each file
    for (const file of files) {
      const filePath = path.join(directory, file);
      const stats = await fs.stat(filePath);
      
      if (stats.isFile()) {
        // Read and process file
        const content = await fs.readFile(filePath, 'utf8');
        await processContent(content);
        
        // Write results
        await fs.writeFile(
          `processed_${file}`,
          processedContent
        );
      }
    }
  } catch (error) {
    console.error('Error processing files:', error);
    throw error;
  }
}

MongoDB Integration

javascript

MongoDB operations with Mongoose

const mongoose = require('mongoose');

// Define schema
const userSchema = new mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);

// Database operations
async function userOperations() {
  try {
    // Connect to database
    await mongoose.connect('mongodb://localhost/myapp');
    
    // Create user
    const user = await User.create({
      name: 'John Doe',
      email: 'john@example.com'
    });
    
    // Find users
    const users = await User.find()
      .sort('-createdAt')
      .limit(10);
    
    // Update user
    await User.findByIdAndUpdate(
      user._id,
      { $set: { name: 'Jane Doe' } },
      { new: true }
    );
    
  } catch (error) {
    console.error('Database error:', error);
  }
}

Authentication Middleware

javascript

JWT authentication middleware

const jwt = require('jsonwebtoken');

const auth = async (req, res, next) => {
  try {
    // Get token from header
    const token = req.header('Authorization')
      .replace('Bearer ', '');
    
    if (!token) {
      throw new Error('No token provided');
    }
    
    // Verify token
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // Find user
    const user = await User.findById(decoded.userId);
    if (!user) {
      throw new Error('User not found');
    }
    
    // Attach user to request
    req.user = user;
    next();
    
  } catch (error) {
    res.status(401).json({
      error: 'Please authenticate'
    });
  }
};

// Usage in routes
app.get('/api/profile', auth, async (req, res) => {
  res.json(req.user);
});