Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to read a file using the built-in Node.js module.
Node.js
const fs = require('fs'); fs.[1]('example.txt', (err, data) => { if (err) throw err; console.log(data.toString()); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using createReadStream instead of readFile for reading entire file at once.
✗ Incorrect
The readFile method reads the entire file into memory before calling the callback.
2fill in blank
mediumComplete the code to create a readable stream from a file.
Node.js
const fs = require('fs'); const stream = fs.[1]('example.txt'); stream.on('data', chunk => { console.log(chunk.toString()); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using readFile which reads the whole file at once.
✗ Incorrect
createReadStream creates a stream to read the file piece by piece.
3fill in blank
hardFix the error in the code to properly handle stream errors.
Node.js
const fs = require('fs'); const stream = fs.createReadStream('example.txt'); stream.on('data', chunk => { console.log(chunk.toString()); }); stream.on('[1]', err => { console.error('Error:', err); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'close' or 'end' event to catch errors.
✗ Incorrect
The error event is emitted when the stream encounters an error.
4fill in blank
hardFill both blanks to pipe a readable stream into a writable stream.
Node.js
const fs = require('fs'); const readable = fs.createReadStream('input.txt'); const writable = fs.[1]('output.txt'); readable.[2](writable);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using writeFile instead of createWriteStream for writable stream.
Calling readFile on readable stream.
✗ Incorrect
createWriteStream creates a writable stream, and pipe connects the readable stream to it.
5fill in blank
hardFill all three blanks to read a file stream and count chunks received.
Node.js
const fs = require('fs'); const stream = fs.[1]('data.txt'); let count = 0; stream.on('[2]', chunk => { count += 1; console.log(`Chunk #$[3] received`); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using readFile instead of createReadStream.
Using 'end' event instead of 'data' for chunks.
✗ Incorrect
createReadStream creates the stream, data event fires for each chunk, and count tracks the number of chunks.