Which of the following best explains why file system access is important in Node.js applications?
Think about what servers need to do with files like logs, configs, or user uploads.
Node.js uses file system access to read and write files on the server. This is essential for storing data, configuration, and handling uploads.
Consider this Node.js code snippet using the fs.promises.readFile method:
import { promises as fs } from 'fs';
async function readData() {
const data = await fs.readFile('data.txt', 'utf8');
console.log(data);
}
readData();What will this code do when run if data.txt exists and contains the text "Hello World"?
Look at how await is used inside an async function.
The code reads the file data.txt asynchronously and waits for the content before printing it. Since the file contains "Hello World", that text is printed.
What error will this Node.js code produce?
import { writeFile } from 'fs';
writeFile('output.txt', 'Test data', (err) => {
if (err) throw err;
console.log('File saved!');
});Check how writeFile is imported from the 'fs' module in Node.js.
No error; writeFile is correctly imported as a named export from fs for the callback-based API. The file will be written asynchronously, and 'File saved!' logged if successful.
Which of the following Node.js code snippets correctly reads a file synchronously and stores its content in content?
Remember synchronous functions do not use callbacks or promises.
readFileSync is the synchronous method to read files in Node.js. It returns the file content directly. The other options either use async methods incorrectly or import from wrong modules.
Given this Node.js code, what will be printed to the console?
import { promises as fs } from 'fs';
async function readFiles() {
const file1 = fs.readFile('file1.txt', 'utf8');
const file2 = fs.readFile('file2.txt', 'utf8');
const content1 = await file1;
const content2 = await file2;
console.log(content1.trim() + ' & ' + content2.trim());
}
readFiles();Assume file1.txt contains "Hello" and file2.txt contains "World" with trailing newlines.
Consider how await works with promises and what trim() does.
The code reads both files asynchronously, waits for their content, trims whitespace including newlines, then joins them with ' & '. The output is "Hello & World".