Nodejs
179 bites tagged Nodejs — interview questions with model answers, and 60-second explainers.
Mongoose: Schemas are Blueprints, Models are Factories
A Mongoose Schema is the blueprint for your data, defining its shape and types. A Model is the factory that uses this blueprint to create, query, and save documents in MongoDB. The common footgun is trying to query the blueprint instead of the factory.
cookie-parser: From Header String to Usable Object
The cookie-parser middleware translates the raw Cookie header string into a usable `req.cookies` object. It's used in Express apps to read session IDs or user preferences.
Morgan: One-Line Request Logging for Express
Morgan is a plug-and-play stenographer for your Express app, automatically logging every incoming HTTP request. Use its predefined formats for quick debugging or create custom formats for production access logs.
CORS Middleware: Unlocking Cross-Origin Requests in Express
The `cors` middleware tells browsers which external websites can read your Express API's responses. Use it when a frontend on one domain needs to fetch data from your API on another.
Express Middleware: Intercepting Requests Before Your Route Handler
Express middleware is like a bouncer for your routes, running code before your main handler. Use it for logging, authentication, or parsing request bodies. The biggest footgun is forgetting to call `next()` or send a response, which leaves requests hanging.
Express Error Middleware: Your App's Safety Net
Express error middleware is a safety net that intercepts unhandled errors, preventing crashes. It's used to centralize logging and format consistent error responses. The biggest footgun is placement: it must be defined *after* all other routes and middleware.
Scaffold an Express App with `express-generator`
The `express-generator` CLI is a blueprint for new Express apps, instantly creating a standard folder structure and boilerplate files. Use it to skip tedious setup of routes and views.
express.Router: Group Routes into Modular Files
express.Router is a mini-app for your routes. It lets you group related endpoints (e.g., all `/users/...` routes) into their own file, keeping your main `app.js` clean. The footgun is forgetting to mount the router in the main app with `app.use()`.
Express Middleware: The Chain of Command for Requests
Express middleware is a chain of functions a request passes through. Each function can inspect, modify, or stop the request, useful for logging, auth, or body parsing.
Express Request and Response Objects (req, res)
Think of Express's `req` and `res` as an incoming letter and your reply. `req` contains the client's request details, like headers and data, while `res` is your toolkit for sending a response. They are the core of every route handler.
Express.js: Basic Request Routing
Express routing connects a request's path and HTTP method (like GET `/`) to a specific handler function. This is the core of any Express app, used to define API endpoints or handle form submissions. A common mistake is using the wrong method for a request.
Creating Your First Express Server
Think of an Express app as three steps: require the library, create an instance, and listen on a port. This is the foundation for any Express-based API or web server.
Node's zlib Module: Trading CPU for Bandwidth
Node's `zlib` module trades CPU cycles for network bandwidth by shrinking data with algorithms like Gzip and Brotli. Use it to compress large API responses or files before sending them. The main footgun: never use synchronous `...Sync` methods in a server.
WHATWG URL API: Safely Parse URLs, Not Strings
Treat URLs as structured objects, not messy strings. The WHATWG URL API parses a URL into components like protocol and path, just like JSON.parse. Use it for incoming requests or outgoing API calls. The footgun is using the legacy `url.parse()`.
path.join() vs. path.resolve(): Concatenation vs. Calculation
path.join() glues path segments together, while path.resolve() calculates an absolute path. Think string building vs. `cd` commands. Use join for relative paths and resolve for absolute ones.
Node.js File I/O: Synchronous vs. Asynchronous
Synchronous file I/O blocks your app, like waiting at a counter for your order. Asynchronous I/O gets a buzzer, letting your app work on other tasks. Use async for servers and sync for simple, one-off scripts. The footgun is using sync I/O in a server.
Node.js util.promisify: From Callbacks to Promises
util.promisify converts callback-based functions into Promise-based ones, letting you use async/await with older Node.js APIs. It's a bridge for legacy code following the standard (err, value) callback pattern. The footgun: it fails on non-standard signatures.
NPM Scopes: Namespacing Packages to Avoid Collisions
NPM scopes act like a personal folder for your packages, using the `@scope/package` format to avoid name collisions. They are essential for publishing private packages for your team or grouping related public ones.
Node.js Circular Dependencies: The Unfinished Export
When module A requires B, and B requires A, Node.js avoids an infinite loop by returning an unfinished version of one module's exports. This happens in complex apps with tightly coupled modules. The code doesn't crash; it fails later with a TypeError.
Environment Variables: Config Outside Your Code
Think of a .env file as a Post-it note of secrets for your app, kept separate from your codebase. Use it for API keys or database URLs that change between environments. The biggest mistake is committing your .env file to Git, exposing all your secrets.
ES Modules in Node.js: The Modern `import` System
ES Modules bring the browser's `import`/`export` syntax to Node.js, replacing the classic `require()`. Use ESM for modern projects to get features like top-level await. The main footgun is that you can't use `require()`, `__dirname`, or `__filename`.
npm Scripts: Your Project's Command-Line Shortcuts
Think of npm scripts as aliases for your project's common command-line tasks, stored in `package.json`. Use them to run build tools, start servers, or execute tests. The main footgun is forgetting `npm run` for custom scripts like `lint` or `build`.
Dependencies vs. DevDependencies: What's the Difference?
Dependencies are packages your app needs to run in production (like a web framework). DevDependencies are for your development workflow (like a test runner). The footgun is mixing them up, which bloats your production build with unnecessary code.
package.json: The Blueprint for Your Node.js Project
The package.json file is the blueprint for a Node.js project, listing its dependencies and runnable scripts. It's essential for installing libraries (`npm install`) and running tasks (`npm test`).
Get Nodejs bites daily.
Five a day, five minutes, offline. With quizzes so it sticks.
Open testing — you’ll join as an early tester.