Nodejs
179 bites tagged Nodejs — interview questions with model answers, and 60-second explainers.
Socket.IO: Emitting and Handling Events
Socket.IO events are named messages sent between a client and server. One side `emit`s a message, the other listens with `on`. This powers real-time apps like chat. The footgun: don't `JSON.stringify` objects; Socket.IO does it for you.
Socket.IO: More Than Just WebSockets
Socket.IO is a library that guarantees real-time, bidirectional communication. It automatically picks the best transport—WebSocket or HTTP long-polling—to ensure your connection works. Use it for chat apps or live dashboards.
V8's Garbage Collector: A Performance Pillar
V8's garbage collector is a key to its speed, using a "stop-the-world, generational, accurate" approach to reclaim memory. This runs automatically in Node.js and Chrome, but its pauses can impact performance.
Node.js perf_hooks: A High-Precision Stopwatch for Your App
The `perf_hooks` module is a high-precision stopwatch for your Node.js code, offering nanosecond accuracy. Use it to benchmark async operations or HTTP request durations.
Backpressure: Don't Drown Your Node.js Streams
Backpressure is flow control for streams, preventing a fast producer from overwhelming a slow consumer, like a traffic light for data. It's crucial when piping a fast file read to a slow network write. Ignoring it causes data to buffer and crash your app.
Preventing SQL Injection: Never Trust User Input
To prevent SQL injection, treat SQL as a template and user input as data that can only fill placeholders, never changing the query's structure. Use this for any database query in your Node.js app that uses external data.
Nock: Intercept and Mock Node.js HTTP Requests
Nock acts like a fake switchboard for your Node.js app's outgoing HTTP calls, redirecting them to pre-defined responses. This lets you unit test code that relies on external services, making tests fast, deterministic, and offline-capable.
Code Coverage Reporting with nyc/Istanbul
Code coverage reporting asks, "Which lines of my code did my tests actually run?" Use a tool like `nyc` to wrap your test runner (e.g., Mocha) and generate a report. The footgun is chasing 100% coverage, which doesn't guarantee quality.
Chai: Assertions for Readable JavaScript Tests
Chai makes your JavaScript tests read like sentences. It provides assertion styles like `expect(value).to.equal(5)` to verify code behavior in test frameworks like Mocha. The main footgun: the `should` style fails silently on null or undefined values.
Mocha: A Flexible JavaScript Test Runner
Mocha is a flexible JavaScript test runner, providing structure but not assertions. It organizes and executes tests in Node.js and browsers, excelling with asynchronous code. The main footgun is forgetting you must pair it with an assertion library like Chai.
Jest: A Batteries-Included JavaScript Test Framework
Jest is a 'batteries-included' JavaScript test framework, bundling a runner, assertions, and mocks for a zero-config experience. It's a go-to for testing Node, React, and TypeScript apps. Footgun: Snapshot tests only catch unexpected changes, not flawed logic.
Node.js Uncaught Exceptions: Clean Up, Don't Continue
An uncaught exception is a fire alarm for your Node.js app, signaling an unknown state. Use the `process.on('uncaughtException')` hook for last-resort synchronous cleanup before exiting, not to resume normal operation.
CSRF Tokens: Preventing Unwanted State Changes on Your Behalf
CSRF protection prevents a malicious site from forcing a user's browser to submit unwanted requests to your app. It adds a unique token to forms that the server validates. The footgun is failing to protect all state-changing endpoints, not just POST forms.
Passport.js: The Generic OAuth2 Strategy
Passport's generic OAuth2 strategy is a template for social logins, not a plug-and-play solution. Use it to integrate a custom OAuth2 provider. The footgun is using it when a provider-specific strategy (like passport-github2) exists, which handles quirks for…
Passport.js: The Local Strategy for Username/Password Auth
Passport's Local Strategy is the bouncer for traditional username/password logins in Node.js. You provide the logic to verify credentials against your database, and Passport handles the session management.
Sequelize Scopes: Reusable Query Shortcuts
Sequelize scopes are named shortcuts for common query conditions, letting you define `where` or `include` clauses once and reuse them. Use them to keep code DRY, like an `active` scope. The footgun: a `defaultScope` is always on unless you call `.unscoped()`.
Mongoose Population: Linking Documents Across Collections
Mongoose's `populate()` acts like a client-side JOIN, replacing document IDs with actual documents from other collections. It's ideal for linking related data, like a blog post's author.
Sequelize Transactions: All-or-Nothing Database Writes
A Sequelize transaction is a safety wrapper for database queries, ensuring they all succeed or none do. Use it for multi-step operations like creating a user and profile.
Sequelize Migrations: Version Control for Your Database
Think of Sequelize migrations as Git for your database schema. Each file is a commit describing how to apply (`up`) and revert (`down`) a change. Use them to evolve your schema reliably across environments. The footgun: never edit the DB directly.
Mongoose Validation: Your Schema's Built-in Guard
Mongoose validation is a guard at the application layer, ensuring data conforms to schema rules before hitting the database. Use it for required fields, lengths, and ranges. The `unique` option is for database indexes, not a Mongoose validation rule.
Mongoose Middleware (Hooks): Intercepting Database Operations
Mongoose middleware (hooks) lets you intercept database operations. Think of them as "before" or "after" scripts for actions like `save` or `find`. Use them to hash passwords before saving a user.
Sequelize Associations: Who Holds the Foreign Key?
Think of Sequelize associations as rules for foreign keys. `A.belongsTo(B)` means `A` holds the `bId` foreign key. `A.hasOne(B)` or `A.hasMany(B)` means `B` holds the `aId` key. The footgun is mixing these up, which breaks your database schema and queries.
Connecting to MongoDB with the Native Node.js Driver
The MongoDB driver is a translator between your Node.js app and database. You create a MongoClient, point it at your database URL, and then you can execute commands. The footgun is not closing the connection, which leads to resource leaks in your application.
API Rate Limiting: Protecting Your Express Endpoints
Rate limiting acts as a bouncer for your API, preventing any single user from overwhelming it. It's crucial for public APIs and sensitive endpoints like password resets to block abuse. The default in-memory store won't work across multiple server instances.
Get Nodejs bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.