內建模組 - 檔案系統 (fs)#

fs(File System)是 Node.js 的內建模組,提供讀取、寫入、刪除、重新命名等檔案與目錄操作功能,不需要安裝即可使用。


1. 匯入 fs 模組#

1
2
3
4
5
6
7
// CommonJS
const fs = require("fs");

// 推薦使用 Promise 版本(fs/promises)
const fs = require("fs").promises;
// 或
const fs = require("fs/promises");

以下範例均使用 fs/promises 搭配 async/await,是現代 Node.js 的推薦寫法。


2. 讀取檔案(readFile)#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const fs = require("fs/promises");

async function readExample() {
    try {
        const content = await fs.readFile("hello.txt", "utf8");
        console.log(content);
    } catch (err) {
        console.error("讀取失敗:", err.message);
    }
}

readExample();
  • 第二個參數 "utf8" 指定編碼,若省略則回傳 Buffer(原始二進制資料)。

3. 寫入檔案(writeFile)#

writeFile 會建立新檔案,若檔案已存在則覆蓋

1
2
3
4
5
6
async function writeExample() {
    await fs.writeFile("output.txt", "Hello, Node.js!\n", "utf8");
    console.log("寫入完成");
}

writeExample();

若要附加內容而非覆蓋,使用 appendFile

1
await fs.appendFile("output.txt", "新增一行\n", "utf8");

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
async function deleteExample() {
    try {
        await fs.unlink("output.txt");
        console.log("刪除成功");
    } catch (err) {
        console.error("刪除失敗:", err.message);
    }
}

deleteExample();

5. 重新命名 / 移動(rename)#

1
await fs.rename("old-name.txt", "new-name.txt");

rename 也可以用來移動檔案,只需提供不同的目錄路徑。


6. 目錄操作#

建立目錄#

1
2
3
4
await fs.mkdir("my-folder");

// 建立多層目錄(如同 mkdir -p)
await fs.mkdir("a/b/c", { recursive: true });

讀取目錄內容#

1
2
const files = await fs.readdir(".");
console.log(files); // ['hello.txt', 'output.txt', ...]

刪除目錄#

1
2
3
4
await fs.rmdir("my-folder");

// 刪除非空目錄
await fs.rm("my-folder", { recursive: true });

7. 取得檔案資訊(stat)#

1
2
3
4
5
6
7
8
9
async function statExample() {
    const info = await fs.stat("hello.txt");
    console.log("是否為檔案:", info.isFile());
    console.log("是否為目錄:", info.isDirectory());
    console.log("檔案大小(bytes):", info.size);
    console.log("最後修改時間:", info.mtime);
}

statExample();

8. 複製檔案(copyFile)#

1
await fs.copyFile("source.txt", "destination.txt");

Reference#