File system access lets your program read and save files on your computer. This is important to keep data, settings, or logs outside the program itself.
Why file system access matters in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
import { promises as fs } from 'fs'; // Read a file const data = await fs.readFile('path/to/file.txt', 'utf-8'); // Write to a file await fs.writeFile('path/to/file.txt', 'Hello world');
Use the 'fs' module in Node.js to work with files.
Use 'await' with promises to handle file operations asynchronously.
Examples
Node.js
import { promises as fs } from 'fs'; // Read a text file async function readFile() { const content = await fs.readFile('notes.txt', 'utf-8'); console.log(content); } readFile();
Node.js
import { promises as fs } from 'fs'; // Write a message to a file async function writeFile() { await fs.writeFile('message.txt', 'Hello from Node.js!'); } writeFile();
Node.js
import { promises as fs } from 'fs'; // Delete a file async function deleteFile() { await fs.unlink('oldfile.txt'); } deleteFile();
Sample Program
This program writes a message to a file, reads it back, prints it, then deletes the file. It shows how to use file system access to save and retrieve data.
Node.js
import { promises as fs } from 'fs'; async function demoFileAccess() { const filename = 'example.txt'; const message = 'This is a test file.'; // Write message to file await fs.writeFile(filename, message); // Read the message back const readMessage = await fs.readFile(filename, 'utf-8'); // Print the content console.log('File content:', readMessage); // Delete the file await fs.unlink(filename); console.log('File deleted.'); } demoFileAccess();
Important Notes
Always handle errors in real apps when working with files to avoid crashes.
Use asynchronous methods to keep your app responsive.
File paths can be absolute or relative to your program's folder.
Summary
File system access lets your app save and load data outside the program.
Node.js provides easy-to-use methods to read, write, and delete files.
Using async file operations keeps your app fast and smooth.
Practice
1. Why is file system access important in a Node.js application?
easy
Solution
Step 1: Understand file system role
File system access lets an app save and retrieve data from files on the computer.Step 2: Identify correct purpose
Only 'It allows the app to save and load data outside the program.' correctly describes this purpose; others are unrelated to file system access.Final Answer:
It allows the app to save and load data outside the program. -> Option DQuick Check:
File system access = save/load data [OK]
Hint: File system means saving or reading files outside code [OK]
Common Mistakes:
- Confusing file system access with CPU or internet features
- Thinking file system fixes bugs automatically
- Assuming file system access speeds up CPU usage
2. Which of the following is the correct way to import the Node.js file system module?
easy
Solution
Step 1: Recall Node.js import syntax
Node.js commonly usesconst fs = require('fs');to import modules in CommonJS style.Step 2: Check options for syntax correctness
'require fs from 'fs';' is invalid syntax; 'import fs from 'fs';' is ES module style but requires extra config; 'const fs = import('fs');' uses dynamic import returning a Promise; 'const fs = require('fs');' matches correct syntax.Final Answer:
const fs = require('fs'); -> Option BQuick Check:
CommonJS import = require('fs') [OK]
Hint: Use require('fs') to import file system in Node.js [OK]
Common Mistakes:
- Using ES module import without config
- Writing invalid syntax like 'require fs from'
- Confusing import() function with require()
3. What will the following Node.js code output?
const fs = require('fs');
fs.writeFileSync('test.txt', 'Hello');
const data = fs.readFileSync('test.txt', 'utf8');
console.log(data);medium
Solution
Step 1: Write data to file synchronously
The code writes 'Hello' to 'test.txt' using writeFileSync, which blocks until done.Step 2: Read file content synchronously
Then it reads the file content as UTF-8 text and stores it indata.Step 3: Output the read content
console.log prints the string 'Hello' read from the file.Final Answer:
Hello -> Option CQuick Check:
Write then read file = 'Hello' output [OK]
Hint: WriteFileSync then ReadFileSync outputs written text [OK]
Common Mistakes:
- Assuming async functions without callbacks
- Expecting undefined or null instead of file content
- Thinking file read fails without prior write
4. Identify the error in this Node.js code snippet:
const fs = require('fs');
fs.readFile('data.txt', (err, data) => {
if (err) throw err;
console.log(data);
});medium
Solution
Step 1: Check readFile usage
fs.readFile without encoding returns a Buffer object, not a string.Step 2: Understand console.log output
Logging Buffer prints raw bytes, not readable text. To get string, encoding like 'utf8' is needed.Final Answer:
Missing encoding, so data is a Buffer, not string. -> Option AQuick Check:
readFile without encoding = Buffer data [OK]
Hint: Add 'utf8' encoding to readFile for string data [OK]
Common Mistakes:
- Ignoring that data is a Buffer without encoding
- Thinking readFile is synchronous
- Assuming callback lacks error parameter
5. You want to read multiple files asynchronously and process their contents only after all are read. Which approach best uses Node.js file system access to achieve this?
hard
Solution
Step 1: Understand asynchronous reading need
Reading files asynchronously avoids blocking the app and keeps it responsive.Step 2: Choose method to track multiple async reads
Using fs.readFile with callbacks and counting completions lets you know when all files are read before processing.Step 3: Eliminate incorrect options
Using fs.readFileSync for each file in a loop blocks until done and is inefficient; using fs.writeFile writes files unnecessarily; using fs.unlink deletes files, which is wrong.Final Answer:
Use fs.readFile with callbacks and count completed reads before processing. -> Option AQuick Check:
Async read with callbacks + count = best approach [OK]
Hint: Use async readFile with callback counting to wait all done [OK]
Common Mistakes:
- Using synchronous reads blocking the app
- Confusing writeFile with reading files
- Deleting files before reading them
