萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 讀寫本地檔案:ActiveXObject 方案 (僅限 IE) 與現代 File API 替代方案

⚠️ 重要前提

原文使用 ActiveXObject("Scripting.FileSystemObject"),**僅在 IE (含 IE 模式) 中於本地檔案/信任站點啟用 ActiveX 時可用**。現代瀏覽器 (Chrome, Firefox, Edge, Safari) **完全不支援**,且極具安全風險 (需降低安全性設定)。**生產環境嚴禁使用。**

原始 IE 專用代碼 (僅供歷史參考)

<script>
function readFile(filename) {
    const fso = new ActiveXObject("Scripting.FileSystemObject");
    const f = fso.OpenTextFile(filename, 1); // 1 = ForReading
    let s = "";
    while (!f.AtEndOfStream) s += f.ReadLine() + "\n";
    f.Close();
    return s;
}

function writeFile(filename, content) {
    const fso = new ActiveXObject("Scripting.FileSystemObject");
    const f = fso.OpenTextFile(filename, 8, true); // 8 = ForAppending, true = create
    f.WriteLine(content);
    f.Close();
    alert('ok');
}
</script>

<input type="text" id="in">
<button onclick="writeFile('c:/12.txt', document.getElementById('in').value)">寫入</button>
<button onclick="document.getElementById('show').value = readFile('c:/12.txt')">讀取</button>
<textarea id="show" cols="50" rows="8"></textarea>

現代瀏覽器標準方案:File API + File System Access API

1. 讀取使用者選取的檔案 (File API - 全瀏覽器支援)

<input type="file" id="fileInput" accept=".txt,.json,.csv">
<textarea id="content" rows="10" cols="60" readonly></textarea>

<script>
document.getElementById("fileInput").addEventListener("change", async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const text = await file.text(); // File API: 非同步讀取文字
    document.getElementById("content").value = text;
});

2. 儲存檔案到使用者下載資料夾 (Blob + a[download])

function saveFile(filename, content) {
    const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    a.click();
    URL.revokeObjectURL(url); // 釋放記憶體
}

<button onclick="saveFile('note.txt', document.getElementById('content').value)">下載儲存</button>

3. 真正的本地檔案系統讀寫:File System Access API (Chrome 86+, Edge 86+)

需使用者透過檔案選擇器授權,獲得 FileSystemHandle 後可隨時讀寫,**無需每次選檔**。

let fileHandle = null;

async function openFile() {
    [fileHandle] = await window.showOpenFilePicker({ types: [{ description: 'Text', accept: { 'text/plain': ['.txt'] } }] });
    const file = await fileHandle.getFile();
    document.getElementById("content").value = await file.text();
}

async function saveFile() {
    if (!fileHandle) {
        [fileHandle] = await window.showSaveFilePicker({ suggestedName: 'note.txt', types: [{ description: 'Text', accept: { 'text/plain': ['.txt'] } }] });
    }
    const writable = await fileHandle.createWritable();
    await writable.write(document.getElementById("content").value);
    await writable.close();
}

<button onclick="openFile()">開啟本地檔案</button>
<button onclick="saveFile()">儲存回原檔案</button>

Node.js 環境讀寫檔案 (伺服器端/建構工具)

// CommonJS
const fs = require("fs/promises");

async function read(file) { return await fs.readFile(file, "utf8"); }
async function write(file, content) { await fs.writeFile(file, content, "utf8"); }

// 同步版 (僅建構腳本/CLI 使用)
const fsSync = require("fs");
fsSync.writeFileSync("a.txt", "hello");
console.log(fsSync.readFileSync("a.txt", "utf8"));

Electron / Tauri / NW.js 桌面應用

主進程擁有完整 Node.js `fs` 權限,渲染進程透過 IPC (preload 腳本) 安全暴露檔案操作給前端:

// preload.js (Context Isolation)
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("fs", {
    read: (path) => ipcRenderer.invoke("fs:read", path),
    write: (path, content) => ipcRenderer.invoke("fs:write", path, content)
});

// 前端使用
const text = await window.fs.read("C:/data/config.json");

方案選擇決策表

場景推薦方案備註
Web 頁面讀取使用者上傳檔案<input type=file> + file.text()標準、安全、全支援
Web 頁面讓使用者下載儲存Blob + a[download]標準、不需權限
Web App 需持續讀寫特定本地檔File System Access APIChrome/Edge 支援,需使用者授權
內網舊系統 僅 IE/IE ModeActiveXObject (HTA/信任站點)**技術債務,規劃遷移**
Node.js 腳本/伺服器/建構工具fs/promises標準非同步 API
Electron/Tauri 桌面應用主進程 fs + Preload IPC安全邊界隔離

安全性鐵律

  1. **網頁無法自動讀寫使用者硬碟** — 必須經過使用者明確互動 (選檔/存檔對話框)。
  2. **拒絕 ActiveX / 降低瀏覽器安全性** — 極高風險,惡意網頁可竊取/破壞系統檔案。
  3. **敏感資料勿存在前端** — Token、密鑰、個資應由後端管理,前端僅暫存於記憶體。

總結

原文的 ActiveX 方案屬於 **IE 時代遺物**,現代 Web 開發請完全轉向 **File API / File System Access API / Node.js fs / 桌面應用 IPC**。理解歷史包袱有助於維護舊系統,但新專案務必採用標準、安全、跨平台的現代 API。

copyright © 萬盛學電腦網 all rights reserved