파일 시스템 액세스
메인 프로세스에서 Node.js의 `fs` 모듈을 사용하여 사용자 시스템의 파일과 디렉터리를 직접 읽고 쓰고 조작하는 방법을 배웁니다.
파일 시스템 액세스은(는) CoddyKit의 무료 Electron Desktop App Development 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Electron Desktop App Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Electron Desktop App Development 강의에는 총 3개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Accessing Local Files
Electron apps can do more than web pages. They can interact directly with the user's computer, including its file system!
This lesson explores how to read, write, and manage files and directories using Node.js's fs module.
Node.js `fs` Module Explained
The fs (File System) module is a core Node.js feature. It provides methods to interact with the file system.
- Reading Files: Get content from existing files.
- Writing Files: Create new files or update existing ones.
- Managing Directories: Create, delete, or list folders.
It's your gateway to persistent local data.
`fs` & The Main Process
For security, you should primarily use the fs module in Electron's main process.
The main process has full Node.js access, while renderer processes (your web pages) are typically sandboxed. This prevents malicious web content from directly accessing user files.
If a renderer needs file access, it should request it securely from the main process via IPC.
Reading Files (`readFileSync`)
The simplest way to read a file is synchronously using fs.readFileSync(). This means your code will pause until the file is read.
Specify the file path and encoding (e.g., 'utf8') to get the content as a string.
const fs = require('fs');
const path = require('path');
// Create a temporary file for demonstration
const tempFilePath = path.join(__dirname, 'hello.txt');
fs.writeFileSync(tempFilePath, 'Hello CoddyKit!', 'utf8');
try {
const content = fs.readFileSync(tempFilePath, 'utf8');
console.log('Read content:', content);
} catch (error) {
console.error('Failed to read file:', error.message);
}
// Clean up the temporary file
fs.unlinkSync(tempFilePath);Writing Files (`writeFileSync`)
To write content to a file, use fs.writeFileSync(). If the file doesn't exist, it will be created. If it does, its content will be overwritten.
Always handle potential errors with try...catch blocks.
const fs = require('fs');
const path = require('path');
const outputFilePath = path.join(__dirname, 'output.txt');
const dataToWrite = 'This is some new content for the file.';
try {
fs.writeFileSync(outputFilePath, dataToWrite, 'utf8');
console.log('File written successfully to', outputFilePath);
} catch (error) {
console.error('Failed to write file:', error.message);
}
// Clean up the temporary file
fs.unlinkSync(outputFilePath);Appending Data (`appendFileSync`)
If you want to add content to the end of an existing file without overwriting it, use fs.appendFileSync().
This is useful for logging or adding new entries to a list.
const fs = require('fs');
const path = require('path');
const logFilePath = path.join(__dirname, 'app.log');
// Ensure the file exists (or create it)
fs.writeFileSync(logFilePath, 'Initial log entry.\n', 'utf8');
const newLogEntry = 'Another event happened now.\n';
try {
fs.appendFileSync(logFilePath, newLogEntry, 'utf8');
console.log('Appended to log file.');
console.log('Current log content:\n', fs.readFileSync(logFilePath, 'utf8'));
} catch (error) {
console.error('Failed to append to file:', error.message);
}
// Clean up the temporary file
fs.unlinkSync(logFilePath);Asynchronous `fs` Methods
Synchronous operations can block your application's main thread, making your UI unresponsive. For better performance, especially with larger files, use asynchronous methods.
fs.readFile() and fs.writeFile() use callbacks or Promises (with fs/promises module) to handle completion.
const fs = require('fs/promises'); // Using promise-based fs
const path = require('path');
const asyncFilePath = path.join(__dirname, 'async_data.txt');
const data = 'Data for async file.';
async function runAsyncOperations() {
try {
await fs.writeFile(asyncFilePath, data, 'utf8');
console.log('Async file written.');
const content = await fs.readFile(asyncFilePath, 'utf8');
console.log('Async file read:', content);
} catch (error) {
console.error('Async operation failed:', error.message);
} finally {
// Clean up
if (await fs.stat(asyncFilePath).then(() => true).catch(() => false)) {
await fs.unlink(asyncFilePath);
}
}
}
runAsyncOperations();Creating & Listing Directories
The fs module also lets you manage directories (folders).
fs.mkdirSync(path, { recursive: true }): Creates a directory.recursive: truecreates parent directories if needed.fs.readdirSync(path): Reads the contents of a directory, returning an array of file/directory names.fs.rmSync(path, { recursive: true, force: true }): Removes a directory (and its contents).
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, 'my_app_data');
const subDirPath = path.join(dirPath, 'logs');
try {
// Create directories
fs.mkdirSync(subDirPath, { recursive: true });
console.log('Directory created:', subDirPath);
// Write a file inside
fs.writeFileSync(path.join(dirPath, 'config.json'), '{ "version": "1.0" }');
fs.writeFileSync(path.join(subDirPath, 'error.log'), 'Error 1\nError 2');
// List contents of dirPath
const contents = fs.readdirSync(dirPath);
console.log('Contents of', dirPath, ':', contents);
} catch (error) {
console.error('Directory operation failed:', error.message);
} finally {
// Clean up
if (fs.existsSync(dirPath)) {
fs.rmSync(dirPath, { recursive: true, force: true });
console.log('Cleaned up directory:', dirPath);
}
}Paths with the `path` Module
File paths differ between operating systems (e.g., /home/user/file.txt on Linux vs. C:\Users\user\file.txt on Windows).
Use Node.js's built-in path module to construct and normalize paths reliably across platforms.
path.join(...segments): Joins path segments.path.resolve(...segments): Resolves a sequence of paths or path segments into an absolute path.
const path = require('path');
const userDir = 'CoddyKitApp';
const dataFile = 'settings.json';
// Correct way to join paths
const fullPath = path.join(userDir, 'data', dataFile);
console.log('Joined path:', fullPath);
// Get absolute path (relative to current working directory)
const absolutePath = path.resolve(userDir, 'data', dataFile);
console.log('Absolute path:', absolutePath);
// Get directory name
console.log('Dir name:', path.dirname(fullPath));
// Get base name (file name with extension)
console.log('Base name:', path.basename(fullPath));File System Challenge
Consider the following Node.js code snippet:
const fs = require('fs');
const path = require('path');
const filePath = path.join(__dirname, 'test_file.txt');
fs.writeFileSync(filePath, 'First line.\n', 'utf8');
fs.appendFileSync(filePath, 'Second line.\n', 'utf8');
const content = fs.readFileSync(filePath, 'utf8');
console.log(content);
fs.unlinkSync(filePath); // Clean up
File System Access Recap
You've learned how to interact with the file system in Electron!
- The
fsmodule is key for file operations. - Perform file operations primarily in the main process for security.
- Distinguish between synchronous (blocking) and asynchronous (non-blocking) methods.
- Use the
pathmodule for cross-platform path management.
This knowledge allows your Electron apps to store and retrieve data directly on the user's machine.
자주 묻는 질문
“파일 시스템 액세스” 강의는 무료인가요?
네 — “파일 시스템 액세스” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Electron Desktop App Development 강의 전체를 잠금 해제할 수 있습니다. Electron Desktop App Development 강의에는 총 3개의 강의가 포함되어 있습니다.
“파일 시스템 액세스”에서 뭘 배우나요?
메인 프로세스에서 Node.js의 `fs` 모듈을 사용하여 사용자 시스템의 파일과 디렉터리를 직접 읽고 쓰고 조작하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Electron Desktop App Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Electron Desktop App Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Electron Desktop App Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.
“파일 시스템 액세스” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Electron Desktop App Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Electron Desktop App Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 로컬 저장소 및 IndexedDB
- 파일 시스템 액세스
- SQLite 임베디드 데이터베이스