檔案 IO
瀏覽器裡的 JS 不能任意讀你硬碟上的檔案;Node.js 可以。日常先會兩件事:用 path 組出路徑,用 fs/promises 讀寫文字。
組路徑
Windows 的路徑用 \,macOS / Linux 用 /。不要自己用字串拼這些符號,改用 path.join,換系統才不容易壞:
import path from "node:path";
const file = path.join(process.cwd(), "notes.txt");
console.log(file);
process.cwd()(current working directory)是你執行 node 時所在的資料夾,不一定是程式檔自己的位置。
讀檔與寫檔
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
const file = path.join(process.cwd(), "notes.txt");
await writeFile(file, "第一行\n", "utf8");
const text = await readFile(file, "utf8");
console.log(text);
- 文字檔請指定
"utf8"。不指定時,讀到的是 Buffer(原始位元組),console.log看起來會像一堆數字,不是中文。 await表示「等這次讀寫做完再往下」。完整說明見 非同步。專案要有"type": "module",才能在檔案最外層直接寫await。
常見狀況
| 狀況 | 處理 |
|---|---|
ENOENT |
檔案或資料夾不存在,先確認路徑與 cwd |
| 中文亂碼 | 讀寫都指定 utf8 |
| 權限錯誤 | 換一個你有寫入權限的資料夾 |
總結
路徑用 path.join,讀寫用 readFile / writeFile,文字加 utf8。先把單一大檔案讀寫做熟,再學資料夾掃描。