JavaScript >> Javascript 文檔 >  >> JavaScript

如何使用 JavaScript 寫入文件,帶有示例

本文將向您展示如何從 JavaScript 寫入文件 – 來自 Web 瀏覽器和 Node.js 環境。附有如何編寫、追加、更新、刪除和重命名文件的示例。

JavaScript 代碼通常從以下兩種環境之一運行——查看網頁時在 Web 瀏覽器中運行,或者在允許 JavaScript 在 Web 瀏覽器之外執行的 Node.js 環境中運行——通常用於構建後端服務和 Web 應用程序.

使用 JavaScript 從瀏覽器寫入文件

首先,如何從瀏覽器中進行操作。現代 JavaScript 包括為此的內置工具。步驟如下:

  • 使用 JavaScript Blob 創建文件 表示文件的對象
  • 為新對象創建一個 URL
  • 提供一個鏈接,用戶可以單擊該鏈接告訴瀏覽器從 URL 下載 Blob 對像作為文件

然後,用戶可以單擊該鏈接,他們將在其網絡瀏覽器中看到標準的保存對話框,允許他們將生成的文件保存在任何他們想要的位置。

以下是代碼看起來是一個可重複使用的函數,您可以復制和粘貼以供自己使用:

// A global variable should be defined to hold the URL for the file to be downloaded
// This is good practice as if many links are being generated or the link is being regularly updated, you don't want to be creating new variables every time, wasting memory
var textFileUrl = null;

// Function for generating a text file URL containing given text
function generateTextFileUrl(txt) {
    let fileData = new Blob([txt], {type: 'text/plain'});

    // If a file has been previously generated, revoke the existing URL
    if (textFileUrl !== null) {
        window.URL.revokeObjectURL(textFile);
    }

    textFileUrl = window.URL.createObjectURL(fileData);

    // Returns a reference to the global variable holding the URL
    // Again, this is better than generating and returning the URL itself from the function as it will eat memory if the file contents are large or regularly changing
    return textFileUrl;
};

// Generate the file download URL and assign it to the link
// Wait until the page has loaded! Otherwise the download link element will not exist
window.addEventListener("load", function(){
    document.getElementById('downloadLink').href = generateTextFileUrl('Hello world!');
});

您需要 HTML 中的以下鏈接來顯示下載按鈕:

<!-- Download link - defaults to # which means clicking it does nothing as no file download link has been assigned (yet) -->
<!-- Note the use of the download attribute! It tells the browser to download the file, and what the default file name should be -->
<a id="downloadLink" href="#" download="myFile.txt">Download</a>

此解決方案不會嘗試模擬單擊生成的鏈接或任何廢話。瀏覽器通常會阻止它,您不應該試圖在用戶沒有明確單擊鏈接以自行保存文件的情況下偷偷下載。

從 Node.js 寫入文件

如果您在 Node.js 環境中工作,則所有用於管理文件的工具都可以在內置的 fs 中使用 圖書館。

讀取或寫入文件需要時間並且可能會停止執行。以前,最好使用回調 在文件被成功讀取或寫入後執行文件操作。

然而,現在,Promises 為異步任務提供了一種標準化的方法。因此,這些示例將使用 Promises 而不是回調來保持現代性。

在編寫現代 JavaScript 時,Promise 非常重要——如果您還不熟悉它們,那麼值得花一兩天時間來熟悉它們。

以下是從 Node.js 編寫文本文件的方法:

// Import the promise-based version of the fs library
const fs = require('fs').promises;

// Define some text to be written to a file
var textData = "Hello world!";

try {
    // Write text to the given file name
    // await tells JavaScript to wait for the asyncronous function (Promise) to resolve before continuing
    await fs.writeFile('myFile.txt', textData); 
} catch (error) {
    // Output any errors for inspection
    console.log(error);
}

請注意使用 try/catch 語句來處理可能發生的任何錯誤。

從 Node.js 附加到文件

從上面開始,使用 fs 很簡單 將數據附加到文件的庫:

const fs = require('fs').promises;

try {
    await fs.appendFile('myFile.txt', textData); 
} catch (error) {
    console.log(error);
}

更新文件

要更新文件,您可以使用 appendFile 追加文件 或使用 writeFile 覆蓋它 ,如上所述。

重命名文件

const fs = require('fs').promises;

try {
    await fs.rename('oldFileName.txt', 'newFileName.txt'); 
} catch (error) {
    console.log(error);
}

刪除文件

取消鏈接 函數將從磁盤中刪除一個文件:

const fs = require('fs').promises;

try {
    await fs.unlink('myFile.txt'); 
} catch (error) {
    console.log(error);
}


Tutorial JavaScript 教程
  1. Javascript 和 Node.js 中的面試問題

  2. Elrond NFT 集合與 Elven 工具

  3. MakeMyTrip 前端機器編碼面試

  4. Array.prototype.at

  5. 如何在 React 中渲染模式

  6. 電子大冒險:第 34 集:應用程序菜單

  7. 開玩笑的三行 Typescript 以獲得類型安全的模擬

  1. 在 5 秒內將 REST API 添加到您的 Vite 服務器

  2. 比較 JS 中的對象

  3. Google Maps API v3(一次打開一個信息窗口)

  4. 如何以角度存儲來自異步管道的結果

  5. TypeError:storage._handleFile 不是函數

  6. 如何將流與管道連接?

  7. 17 個最佳 WordPress 聯繫表單插件(經過審查和比較)

  1. 面試準備——基本 JavaScript-1

  2. 我們如何打造更好的搜索體驗

  3. Angular vs NPM vs Node.js

  4. 在 React Native 中使用 firebase 存儲用戶在線狀態的自定義鉤子