Core Node.js Modules

15 questions found

What is the node: prefix for core module imports, and why was it introduced?

Beginner
The node: prefix explicitly signals a built-in core module rather than a third-party package -- introduced partly to remove ambiguity in module resolution and support scenarios where explicitly distinguishing core modules from userland packages matters; older unprefixed requires still work for compatibility.
const fs = require('node:fs');
const fs2 = require('fs'); // still works, older style
Real-world example A team adopts the node: prefix so a linter rule can flag accidental shadowing of a core module name by a local file, making core-module imports visually unambiguous.

Common follow-ups: Is the node: prefix required or merely a stylistic convention currently?;Are there core modules that specifically require the node: prefix?

Modules (CommonJS/ESM);File System (fs) Module

What is the util module's inspect() function used for, and how does it relate to how console.log() displays objects?

Beginner
util.inspect() converts a value into a formatted, human-readable string, including nested objects -- it's what console.log() uses internally (rather than JSON.stringify, which can't handle circular references or non-JSON types), and can be called directly for custom formatting needs like controlling nesting depth.
const obj = { name: 'Alice', nested: { deep: { value: 42 } } };
console.log(util.inspect(obj, { depth: 1, colors: true }));
Real-world example A logging utility uses util.inspect() with a bounded depth to safely log deeply nested request objects without crashing on a circular reference, which JSON.stringify would throw on.

Common follow-ups: Why does JSON.stringify() throw on a circular reference while console.log() handles it gracefully?;How would you define a custom inspection format using util.inspect.custom?

Debugging & Diagnostics;JSON & Data Serialization

What does the node:path module provide, and why should you always use it instead of manually concatenating file path strings?

Intermediate
The path module provides platform-aware utilities -- join(), resolve(), dirname(), extname() -- that correctly handle the difference between path separators on different OSes, whereas manual string concatenation with a hardcoded '/' would break on Windows.
const filePath = path.join(__dirname, 'data', 'users.json');
console.log(path.extname(filePath));
Real-world example A CLI tool that manually concatenated paths worked on macOS but broke on Windows until every path operation was replaced with path.join(), which uses the correct separator per OS.

Common follow-ups: What's the difference between path.join() and path.resolve() regarding relative versus absolute output?;How does path.normalize() clean up redundant segments like '../'?

File System (fs) Module;CLI Tools & Scripting with Node.js

What does the node:crypto module provide, and what's the difference between hashing and encryption?

Intermediate
crypto provides hashing (createHash), symmetric/asymmetric encryption, HMAC signing, and secure random generation. Hashing is one-way, producing a fixed-size fingerprint that can't be reversed; encryption is reversible, transforming data into ciphertext decryptable back to plaintext given the correct key.
const hash = crypto.createHash('sha256').update('some data').digest('hex');
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
Real-world example A file-integrity checker computes a SHA-256 hash to verify a download wasn't corrupted, while a separate feature encrypts stored API credentials with AES-256-GCM so they can be decrypted later.

Common follow-ups: Why is crypto.randomBytes() preferred over Math.random() for security-sensitive values?;What does 'GCM' in AES-256-GCM provide beyond basic encryption?

Security;Authentication & Authorization (JWT OAuth Passport)

What does the URL/URLSearchParams API provide, and why is it generally preferred over the older querystring module today?

Beginner
URL and URLSearchParams (globally available, matching the browser API) provide a complete, spec-compliant way to parse a URL and manipulate query strings, handling edge cases like encoding more consistently than the legacy querystring module.
const url = new URL('https://example.com/search?q=nodejs');
console.log(url.searchParams.get('q'));
const params = new URLSearchParams();
params.append('name', 'Alice');
Real-world example An HTTP client builds request query strings using URLSearchParams rather than manual concatenation, automatically getting correct percent-encoding of special characters.

Common follow-ups: In what situations does the legacy querystring module still get used in modern codebases?;How does URLSearchParams handle a parameter appearing multiple times with the same key?

HTTP & HTTPS Modules;RESTful API Design with Express

What does the node:assert module provide, and how does it differ in purpose from a full testing framework?

Intermediate
assert provides basic assertion functions that throw an AssertionError when unmet -- a low-level building block used as the assertion layer inside test suites, but it doesn't provide test organization, running, or reporting the way a full framework like Jest does.
assert.strictEqual(2 + 2, 4);
assert.deepStrictEqual({ a: 1 }, { a: 1 });
Real-world example A team using node:test pairs it with node:assert for assertions, avoiding an external assertion library for a minimal, dependency-light testing setup.

Common follow-ups: How does assert.strictEqual() differ from assert.deepStrictEqual() when comparing objects?;Why might a team still choose Jest's or Chai's assertion syntax despite the added dependency?

Testing with Jest Mocha & the Node Test Runner;Error Handling

What is the node:stream module's Transform stream, and how does it differ from a Readable or Writable stream?

Advanced
A Transform stream is both readable and writable, taking input, transforming it (via a required _transform() method), and making the result readable out the other side -- unlike a plain Readable or Writable, it sits naturally in the middle of a pipeline, standard for compression, encryption, or format conversion as streaming steps.
const uppercaseTransform = new Transform({
  transform(chunk, encoding, callback) {
    this.push(chunk.toString().toUpperCase());
    callback();
  },
});
readableStream.pipe(uppercaseTransform).pipe(writableStream);
Real-world example A log-processing pipeline pipes raw log lines through a custom Transform that redacts sensitive fields, processed incrementally without loading the entire file into memory.

Common follow-ups: What is the difference between a Transform stream's 'transform' mode and its 'flush' behavior?;How would you implement a Transform that buffers multiple chunks before producing output, like a line-splitter?

Streams & Buffers;File System & File Processing

What does the node:os module provide, and what are some commonly used functions from it?

Beginner
os exposes OS-level info: platform() (OS name), cpus() (core details), totalmem()/freemem() (memory stats), homedir(), and tmpdir() -- useful for cross-platform scripts, sizing worker pools, and diagnostic logging.
console.log('Platform:', os.platform());
console.log('Free memory (GB):', (os.freemem() / 1e9).toFixed(2));
Real-world example A monitoring script logs os.freemem() and os.cpus().length to help diagnose whether periodic slowdowns stem from low memory or insufficient CPU cores.

Common follow-ups: How does os.tmpdir() behave differently across Windows, macOS, and Linux?;What's the difference between os.uptime() and process.uptime()?

Path & OS Modules;CLI Tools & Scripting with Node.js

What does the node:zlib module provide, and how would you use it to compress an HTTP response?

Intermediate
zlib provides compression/decompression (gzip, deflate, Brotli) -- commonly used to compress HTTP responses reducing bandwidth, with Accept-Encoding indicating client support, though in Express this is typically handled via the compression middleware.
fs.createReadStream('large-file.txt').pipe(zlib.createGzip()).pipe(fs.createWriteStream('large-file.txt.gz'));

app.use(require('compression')());
Real-world example An API serving large JSON payloads adds the compression middleware, reducing typical response sizes by 70-80% and improving load times on slower connections.

Common follow-ups: How does Brotli compare to gzip in compression ratio and CPU cost?;When might compressing a response hurt performance, such as for already-compressed binary content?

HTTP & HTTPS Modules;Performance Optimization & Profiling

What is the node:vm module, and what are the security implications of using it to execute untrusted code?

Advanced
vm compiles and runs JavaScript within a separate V8 context, often for sandboxing -- but its isolation is not a genuine hardened security boundary, since code running inside can, through known techniques, escape into the surrounding process in certain configurations, so it shouldn't be the sole defense for truly untrusted code.
vm.createContext(context);
vm.runInContext('result = 2 + 2;', context);
Real-world example A low-code platform initially ran user formula scripts via vm alone, but moved to a separate resource-limited child process after a security review found vm's isolation alone insufficient.

Common follow-ups: What are documented ways code can escape a vm context?;What are more robust alternatives like isolated-vm or a separate process/container?

Security;Child Processes & Process Management

Showing 1–10 of 15