Node.js Frequently Asked Questions (FAQ)

General Questions

What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside a web browser. It allows developers to use JavaScript to write command-line tools and 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.

Why was Node.js created?

Node.js was created by Ryan Dahl in 2009 to address the limitations of traditional web servers that used a thread-based model for handling concurrent connections. Node.js introduced an event-driven, non-blocking I/O model that makes it lightweight and efficient for building scalable network applications.

Is Node.js single-threaded?

Node.js applications run on a single thread for JavaScript execution, but they can handle multiple concurrent operations through asynchronous I/O and the event loop. Additionally, Node.js provides APIs like worker_threads and child_process to utilize multiple CPU cores when needed.

What is npm?

npm (Node Package Manager) is the default package manager for Node.js and the world's largest software registry. It allows developers to share and reuse code packages, manage dependencies, and run scripts defined in package.json files.

Installation and Setup

Which version should I install: LTS or Current?

  • LTS (Long-Term Support): Recommended for production applications. Provides stability, security updates, and long-term support (30 months total).
  • Current: Contains the latest features but has a shorter support cycle. Best for development, testing new features, or learning.

How do I switch between Node.js versions?

Use a Node version manager:

  • nvm (macOS/Linux): nvm install 18 && nvm use 18
  • nvm-windows (Windows): Similar commands to Unix-based nvm
  • fnm (Fast Node Manager): Cross-platform alternative with better performance

Why am I getting permission errors when installing global packages?

This typically happens when npm tries to write to system directories that require elevated permissions. Solutions:

  1. Configure npm to use a different directory: npm config set prefix ~/.npm-global
  2. Add ~/.npm-global/bin to your PATH
  3. Use a Node version manager that handles permissions properly

How do I verify my Node.js installation?

Run these commands in your terminal:

node --version    # Shows Node.js version
npm --version     # Shows npm version
node -e "console.log('Working!')"  # Tests basic functionality

Development Questions

What is the difference between CommonJS and ES Modules?

  • CommonJS (require()/module.exports): The original Node.js module system, synchronous, widely supported
  • ES Modules (import/export): Modern JavaScript standard, asynchronous, requires .mjs extension or "type": "module" in package.json

Example CommonJS:

// math.js
exports.add = (a, b) => a + b;

// app.js
const { add } = require('./math');

Example ES Modules:

// math.mjs
export const add = (a, b) => a + b;

// app.mjs
import { add } from './math.mjs';

How do I handle asynchronous operations?

Three main approaches:

  1. Callbacks (traditional but can lead to "callback hell"):
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});
  1. Promises (better error handling and chaining):
fs.promises.readFile('file.txt', 'utf8')
  .then(data => console.log(data))
  .catch(err => console.error(err));
  1. Async/Await (most readable, looks synchronous):
async function readFile() {
  try {
    const data = await fs.promises.readFile('file.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

What is the event loop and how does it work?

The event loop is Node.js's mechanism for handling asynchronous operations without blocking the main thread. It continuously checks for pending callbacks and executes them when their associated operations complete.

Phases of the event loop:

  1. Timers: Execute setTimeout() and setInterval() callbacks
  2. Pending callbacks: Execute I/O callbacks deferred to the next loop iteration
  3. Idle, prepare: Internal use only
  4. Poll: Retrieve new I/O events; execute I/O-related callbacks
  5. Check: Execute setImmediate() callbacks
  6. Close callbacks: Execute close event callbacks (e.g., socket.on('close'))

How do I debug Node.js applications?

Multiple debugging options:

  1. Built-in inspector: node --inspect app.js
  2. Chrome DevTools: Connect to chrome://inspect
  3. VS Code debugger: Built-in Node.js debugging support
  4. Console logging: Simple but effective for basic debugging
  5. Dedicated debugging tools: Like Node.js Inspector Manager (NiM)

Performance and Scaling

How do I scale Node.js applications?

Several strategies:

  1. Clustering: Use the built-in cluster module to create child processes that share server ports
  2. Load balancing: Use reverse proxies like NGINX to distribute traffic across multiple Node.js instances
  3. Microservices: Break large applications into smaller, independent services
  4. Caching: Implement caching layers (Redis, Memcached) to reduce database load
  5. Database optimization: Use connection pooling and query optimization

What causes memory leaks in Node.js?

Common causes:

  • Global variables: Accumulating data in global scope
  • Unclosed event listeners: Not removing event listeners when objects are destroyed
  • Closures: Holding references to large objects longer than necessary
  • Timers: Not clearing intervals and timeouts
  • Buffers: Not properly managing large binary data

Detection tools:

  • process.memoryUsage() for basic monitoring
  • Heap snapshots with Chrome DevTools
  • Memory profiling tools like Clinic.js

How do I handle CPU-intensive tasks?

Since Node.js is single-threaded for JavaScript execution, CPU-intensive tasks can block the event loop. Solutions:

  1. Worker Threads: Use the worker_threads module for parallel processing
const { Worker } = require('worker_threads');
const worker = new Worker('./cpu-intensive-task.js');
  1. Child Processes: Spawn separate processes using child_process
const { spawn } = require('child_process');
const child = spawn('python', ['script.py']);
  1. Offload to external services: Use message queues (RabbitMQ, Kafka) to process heavy tasks asynchronously

  2. Optimize algorithms: Profile and optimize the actual code causing performance issues

Security

How do I secure my Node.js application?

Key security practices:

  1. Input validation: Always validate and sanitize user input
  2. Dependency management: Regularly update dependencies and run npm audit
  3. Environment variables: Store secrets in environment variables, never in code
  4. Rate limiting: Prevent brute force attacks with rate limiting middleware
  5. Helmet.js: Use security headers middleware
  6. CORS: Properly configure Cross-Origin Resource Sharing
  7. HTTPS: Always use HTTPS in production
  8. Authentication: Implement proper authentication and authorization

How do I prevent common vulnerabilities?

  • SQL Injection: Use parameterized queries or ORMs
  • XSS (Cross-Site Scripting): Escape user input before rendering
  • CSRF (Cross-Site Request Forgery): Use CSRF tokens
  • Prototype pollution: Avoid unsafe object merging functions
  • Path traversal: Validate file paths and use path.resolve() with caution

Deployment and Production

What process manager should I use?

Popular options:

  1. PM2: Most popular, feature-rich, supports clustering and monitoring
  2. Forever: Simple process manager, good for basic use cases
  3. Systemd: Native Linux service manager, integrates well with the OS
  4. Docker: Containerization approach, excellent for microservices

How do I handle environment-specific configuration?

Use environment variables and configuration files:

// config.js
const config = {
  development: {
    port: 3000,
    dbUrl: 'mongodb://localhost:27017/myapp'
  },
  production: {
    port: process.env.PORT || 8080,
    dbUrl: process.env.DATABASE_URL
  }
};

module.exports = config[process.env.NODE_ENV || 'development'];

What monitoring tools should I use?

  • Application Performance Monitoring (APM): New Relic, Datadog, AppSignal
  • Logging: Winston, Bunyan, with centralized logging (ELK stack, Splunk)
  • Health checks: Custom endpoints that verify application health
  • Metrics: Prometheus with Grafana for visualization
  • Error tracking: Sentry, Rollbar for exception monitoring

How do I implement graceful shutdown?

Handle process signals to clean up resources:

const server = http.createServer(app);

const shutdown = () => {
  server.close(() => {
    console.log('Server closed');
    process.exit(0);
  });
  
  // Force shutdown after 10 seconds
  setTimeout(() => {
    console.error('Could not close connections in time, forcefully shutting down');
    process.exit(1);
  }, 10000);
};

process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);

Ecosystem and Community

  • Express.js: Minimalist, flexible, most widely used
  • Fastify: High-performance, low overhead
  • Koa: Modern, uses async/await, from Express creators
  • NestJS: TypeScript-first, enterprise-grade architecture
  • Hapi: Configuration-centric, enterprise-focused

How do I contribute to Node.js?

Ways to contribute:

  1. Code contributions: Fix bugs, implement features (requires CLA)
  2. Documentation: Improve docs, tutorials, and examples
  3. Testing: Write and improve test coverage
  4. Community support: Help others on forums, Stack Overflow
  5. Evangelism: Present at meetups, write blog posts
  6. Working groups: Join official Node.js working groups

Start by visiting the Node.js GitHub repository and reading the contribution guidelines.

Where can I find learning resources?

  • Official documentation: https://nodejs.org/en/docs/
  • Node.js Learn: https://nodejs.org/en/learn/
  • NodeSchool: Interactive workshops and tutorials
  • Books: "Node.js Design Patterns", "Mastering Node.js"
  • Online courses: Udemy, Pluralsight, freeCodeCamp
  • Communities: Node.js Discord, Reddit r/node, local meetups