0
0
Node.jsframework~5 mins

Reading files with promises (fs.promises) in Node.js - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is fs.promises in Node.js?

fs.promises is a part of Node.js that provides file system methods which return promises. This lets you use async/await or .then() for easier asynchronous file operations.

Click to reveal answer
beginner
How do you read a file using fs.promises with async/await?

You use await fs.promises.readFile(path, options) inside an async function. It returns the file content as a buffer or string if encoding is set.

Click to reveal answer
intermediate
Why is using promises better than callbacks for reading files?

Promises make code easier to read and write by avoiding nested callbacks. They allow chaining and use of async/await, which looks like normal synchronous code but runs asynchronously.

Click to reveal answer
intermediate
What happens if the file does not exist when using fs.promises.readFile?

The promise is rejected with an error. You can catch this error using try/catch with async/await or .catch() when using promises.

Click to reveal answer
beginner
Show a simple example of reading a text file with fs.promises and logging its content.
<pre>import { promises as fs } from 'fs';

async function readText() {
  try {
    const data = await fs.readFile('file.txt', 'utf8');
    console.log(data);
  } catch (err) {
    console.error('Error reading file:', err);
  }
}

readText();</pre>
Click to reveal answer
Which method from fs.promises reads a file asynchronously?
AreadFile
BreadFileSync
Copen
DwriteFile
What does fs.promises.readFile return when successful?
AA callback function
BFile descriptor number
CUndefined
DA promise that resolves to file content
How do you handle errors when using async/await with fs.promises.readFile?
AUsing if/else
BUsing try/catch block
CUsing switch statement
DNo error handling needed
Which import syntax correctly imports fs.promises in ES modules?
Aimport fs from 'fs/promises';
Bconst fs = require('fs').promises;
Cimport { promises as fs } from 'fs';
Dimport fs from 'fs';
What encoding option should you pass to readFile to get a string instead of a buffer?
A'utf8'
B'ascii'
C'base64'
DNo option needed
Explain how to read a file asynchronously using fs.promises and handle errors.
Think about using async/await and try/catch blocks.
You got /4 concepts.
    Describe the benefits of using promises over callbacks when reading files in Node.js.
    Focus on code readability and error management.
    You got /4 concepts.