0
0
Node.jsframework~10 mins

Streams vs loading entire file in memory in Node.js - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AcreateReadStream
BappendFile
CreadFile
DwriteFile
Attempts:
3 left
💡 Hint
Common Mistakes
Using createReadStream instead of readFile for reading entire file at once.
2fill in blank
medium

Complete 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'
AcreateReadStream
BappendFile
CwriteFile
DreadFile
Attempts:
3 left
💡 Hint
Common Mistakes
Using readFile which reads the whole file at once.
3fill in blank
hard

Fix 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'
Aclose
Berror
Cend
Dfinish
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'close' or 'end' event to catch errors.
4fill in blank
hard

Fill 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'
AcreateWriteStream
BreadFile
Cpipe
DwriteFile
Attempts:
3 left
💡 Hint
Common Mistakes
Using writeFile instead of createWriteStream for writable stream.
Calling readFile on readable stream.
5fill in blank
hard

Fill 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'
AcreateReadStream
Bdata
Ccount
DreadFile
Attempts:
3 left
💡 Hint
Common Mistakes
Using readFile instead of createReadStream.
Using 'end' event instead of 'data' for chunks.