Step 1: Understand readFileSync output with encoding
When readFileSync is called with 'utf8' encoding, it returns a string containing the file content.
Step 2: Check typeof operator on string
typeof on a string returns 'string'.
Final Answer:
'string' -> Option A
Quick Check:
readFileSync with 'utf8' returns string [OK]
Hint: readFileSync with 'utf8' returns string type [OK]
Common Mistakes:
Assuming output is a Buffer without encoding
Confusing typeof output with file content
Expecting 'object' or 'buffer' instead of 'string'
4. Identify the error in this code snippet that reads a file synchronously:
const data = fs.readFileSync('data.txt');
console.log(data.toString('utf8'));
medium
A. fs module is not imported correctly.
B. toString() should not have 'utf8' as argument here.
C. Missing encoding in readFileSync causes error.
D. readFileSync requires a callback function.
Solution
Step 1: Check the import statement
The code snippet is missing the line to import the fs module: const fs = require('fs');
Step 2: Consequence of missing import
Without importing fs, fs.readFileSync will throw ReferenceError: fs is not defined.
Step 3: Why other options are incorrect
A: readFileSync is synchronous, no callback needed. B: Without encoding, returns Buffer; Buffer.toString('utf8') is valid. C: Missing encoding returns Buffer, no error.
Final Answer:
fs module is not imported correctly. -> Option A
Quick Check:
Missing fs import causes ReferenceError [OK]
Hint: Require 'fs' module before using fs methods [OK]
Common Mistakes:
Thinking readFileSync needs a callback
Assuming missing encoding causes error
Believing toString cannot take encoding argument
5. You want to read a small configuration file synchronously and handle errors properly. Which code snippet correctly does this?
hard
A. const fs = require('fs');
const config = fs.readFileSync('config.json');
console.log(config.toString());
B. const fs = require('fs');
const config = fs.readFileSync('config.json', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});