Bird
Raised Fist0
Node.jsframework~20 mins

Built-in modules overview in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Node.js Built-in Modules Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of using the 'path' module to join paths
What is the output of this Node.js code snippet using the built-in path module?
Node.js
import path from 'path';
console.log(path.join('folder', 'subfolder', 'file.txt'));
A'folder\\subfolder\\file.txt'
B'folder.subfolder.file.txt'
C'folder-subfolder-file.txt'
D'folder/subfolder/file.txt'
Attempts:
2 left
💡 Hint
Think about how the path.join method works on Windows systems.
component_behavior
intermediate
2:00remaining
Behavior of the 'fs' module's readFileSync method
What happens when you run this Node.js code using the fs module's readFileSync method on a non-existent file?
Node.js
import fs from 'fs';
try {
  const data = fs.readFileSync('nofile.txt', 'utf8');
  console.log(data);
} catch (err) {
  console.log('Error caught');
}
AThrows an uncaught exception and stops execution
BPrints 'undefined' if file does not exist
CPrints the file content if exists, otherwise prints 'Error caught'
DCreates an empty file named 'nofile.txt' and prints nothing
Attempts:
2 left
💡 Hint
Consider how readFileSync behaves when the file is missing and how the try-catch block works.
📝 Syntax
advanced
2:00remaining
Correct import syntax for the 'os' module in Node.js ES modules
Which option shows the correct way to import the built-in os module in a Node.js ES module environment?
Aimport * as os from 'os';
Bconst os = require('os');
Cimport os from 'os';
Dimport { os } from 'node:os';
Attempts:
2 left
💡 Hint
Remember that require is not used in ES modules and how to import entire modules.
🔧 Debug
advanced
2:00remaining
Identify the error in this 'http' server code snippet
What error will this Node.js code produce when run, and why?
Node.js
import http from 'http';
const server = http.createServer((req, res) => {
  res.write('Hello World');
  res.end();
});
server.listen(3000);
console.log('Server running on port 3000');

// Later in code
server.listen(3000);
ARuns fine and prints 'Server running on port 3000' twice
BServer listens on two ports simultaneously without error
CThrows a SyntaxError due to duplicate listen calls
DThrows an error: 'Error: listen EADDRINUSE: address already in use 3000'
Attempts:
2 left
💡 Hint
Think about what happens if you try to listen on the same port twice.
🧠 Conceptual
expert
3:00remaining
Understanding the behavior of the 'events' module with multiple listeners
Consider this Node.js code using the events module. What will be the output when the event is emitted?
Node.js
import EventEmitter from 'events';
const emitter = new EventEmitter();
emitter.on('ping', () => console.log('First listener'));
emitter.once('ping', () => console.log('Second listener'));
emitter.emit('ping');
emitter.emit('ping');
ASecond listener\nFirst listener\nSecond listener
BFirst listener\nSecond listener\nFirst listener
CFirst listener\nFirst listener
DSecond listener\nSecond listener
Attempts:
2 left
💡 Hint
Remember the difference between on and once listeners.

Practice

(1/5)
1. Which statement best describes Node.js built-in modules?
easy
A. They require manual compilation before use.
B. They must be downloaded separately before use.
C. They are only available through third-party packages.
D. They are pre-installed tools for common tasks in Node.js.

Solution

  1. Step 1: Understand what built-in modules are

    Built-in modules come with Node.js by default and provide common functionalities without extra installation.
  2. Step 2: Compare options with this fact

    Only 'They are pre-installed tools for common tasks in Node.js.' correctly states they are pre-installed tools. Others mention downloading, third-party, or compiling, which are incorrect.
  3. Final Answer:

    They are pre-installed tools for common tasks in Node.js. -> Option D
  4. Quick Check:

    Built-in modules = pre-installed tools [OK]
Hint: Built-in means included by default, no download needed [OK]
Common Mistakes:
  • Thinking built-in modules need separate installation
  • Confusing built-in with third-party packages
  • Assuming manual compilation is required
2. Which is the recommended way to import the built-in fs module in Node.js using ES modules?
easy
A. import fs from 'fs';
B. import fs from 'node:fs';
C. import { fs } from 'fs';
D. const fs = require('fs');

Solution

  1. Step 1: Identify ES module import syntax for built-in modules

    Node.js recommends using the node: prefix with ES module import syntax for built-in modules.
  2. Step 2: Check options for correct syntax

    import fs from 'node:fs'; uses import fs from 'node:fs'; which is correct. import fs from 'fs'; misses the prefix, B uses CommonJS syntax, C incorrectly destructures.
  3. Final Answer:

    import fs from 'node:fs'; -> Option B
  4. Quick Check:

    Use import + node: prefix for built-in modules [OK]
Hint: Use 'import' with 'node:' prefix for built-in modules [OK]
Common Mistakes:
  • Using CommonJS require() in ES modules
  • Omitting 'node:' prefix for built-in modules
  • Incorrect destructuring import syntax
3. What will the following code output?
import os from 'node:os';
console.log(os.platform());
medium
A. The current operating system platform, like 'win32' or 'linux'.
B. An error because 'os' is not a valid module.
C. Undefined because platform() is not a function.
D. The Node.js version number.

Solution

  1. Step 1: Understand the 'os' module and platform() method

    The 'os' built-in module provides operating system info. The platform() method returns the OS platform string.
  2. Step 2: Analyze the code output

    The code imports 'os' correctly and calls platform(), so it prints the OS platform like 'win32', 'linux', or 'darwin'.
  3. Final Answer:

    The current operating system platform, like 'win32' or 'linux'. -> Option A
  4. Quick Check:

    os.platform() returns OS platform string [OK]
Hint: os.platform() returns your system's platform name [OK]
Common Mistakes:
  • Thinking 'os' is not built-in
  • Assuming platform() is undefined
  • Confusing platform() with Node.js version
4. Identify the error in this code snippet:
import path from 'node:path';
const fullPath = path.join('/home', 'user', 123);
console.log(fullPath);
medium
A. The number 123 should be a string to join paths correctly.
B. The import statement is incorrect; 'node:path' is invalid.
C. path.join cannot join more than two arguments.
D. console.log is missing parentheses.

Solution

  1. Step 1: Check the import statement

    Importing 'path' from 'node:path' is correct syntax for built-in modules.
  2. Step 2: Analyze path.join arguments

    path.join expects string arguments. Passing number 123 relies on implicit string coercion, which is not best practice and can lead to unexpected results.
  3. Step 3: Identify the error

    Best practice is to convert 123 to string before joining paths to avoid issues.
  4. Final Answer:

    The number 123 should be a string to join paths correctly. -> Option A
  5. Quick Check:

    path.join needs string args, numbers cause issues [OK]
Hint: All path.join args must be strings, not numbers [OK]
Common Mistakes:
  • Thinking 'node:path' import is invalid
  • Believing path.join limits arguments
  • Missing parentheses in console.log
5. You want to read a file asynchronously using the built-in fs module with promises. Which code snippet correctly imports and uses it?
hard
A. import fs from 'node:fs'; fs.readFile('file.txt', (err, data) => { console.log(data); });
B. import fs from 'fs'; const data = fs.readFileSync('file.txt'); console.log(data);
C. import { readFile } from 'node:fs/promises'; const data = await readFile('file.txt', 'utf8'); console.log(data);
D. const fs = require('fs/promises'); fs.readFile('file.txt').then(console.log);

Solution

  1. Step 1: Identify correct import for promise-based fs

    Node.js provides promise-based fs functions under 'node:fs/promises' module, imported with ES module syntax.
  2. Step 2: Check usage of readFile with await

    import { readFile } from 'node:fs/promises'; const data = await readFile('file.txt', 'utf8'); console.log(data); correctly imports readFile from 'node:fs/promises' and uses await to read file asynchronously.
  3. Step 3: Verify other options

    import fs from 'node:fs'; fs.readFile('file.txt', (err, data) => { console.log(data); }); uses callback style, not promises. import fs from 'fs'; const data = fs.readFileSync('file.txt'); console.log(data); uses synchronous readFileSync. const fs = require('fs/promises'); fs.readFile('file.txt').then(console.log); uses require() which is CommonJS, not ES modules.
  4. Final Answer:

    import { readFile } from 'node:fs/promises'; const data = await readFile('file.txt', 'utf8'); console.log(data); -> Option C
  5. Quick Check:

    Use 'node:fs/promises' with await for async file read [OK]
Hint: Use 'node:fs/promises' and await for async file reading [OK]
Common Mistakes:
  • Using callback style instead of promises
  • Mixing CommonJS require with ES modules
  • Using synchronous readFileSync for async needs