當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js fs-extra outputFile()用法及代碼示例

outputFile()函數將數據寫入給定文件。它與writeFile()函數相似,不同之處在於,如果不存在必須向其寫入數據的文件,則該文件將由該函數本身創建。即使該文件位於不存在的目錄中,它也將由函數本身創建。

用法:

fs.outputFile(file,data,options,callback)

參數:該函數接受上述和以下所述的四個參數。

  • file:它是一個字符串,它定義了必須在其中寫入文件的路徑。
  • data:它是將寫入文件的字符串,Buffer,TypedArray或DataView。
  • options:它是用於指定可選參數的字符串或對象。可用的選項有:
  • callback:函數完成任務後將調用它。這將導致錯誤或成功。也可以用Promise代替回調函數。
  1. encoding:它是一個定義文件編碼的字符串。默認情況下,該值為 utf-8。

  2. mode:它是一個定義文件模式的整數值。默認情況下,該值為 0o666。

  3. flag:它是一個字符串值,用於定義寫入文件時使用的標誌。默認情況下,該值為 ‘w’。您可以在此處檢查標誌。

  4. signal:AbortSignal 允許中止 in-progress 輸出文件。

返回值:它不返回任何東西。

請按照以下步驟實現該函數:

  1. 可以使用以下命令安裝該模塊:

    npm install fs-extra
  2. 安裝模塊後,可以使用以下命令檢查已安裝模塊的版本:

    npm ls fs-extra

  3. 使用以下命令創建一個名稱為index.js的文件,並在文件中需要fs-extra模塊

    const fs = require('fs-extra');
  4. 要運行文件,請在終端中輸入以下命令:

    node index.js

項目結構將如下所示:

範例1:

index.js


// Requiring module
import  fs from "fs-extra";
  
// file already exist
// so data will be written
// onto the file
const file = "file.txt";
  
// This data will be
// written onto file
const data = "This is geeksforgeeks";
  
// Function call
// Using callback function
fs.outputFile(file, data, (err) => {
  if (err) return console.log(err);
  console.log("Data successfully written onto the file");
  console.log("Written data is:");
  //   Reading data after writing on file
  console.log(fs.readFileSync(file, "utf-8"));
});

輸出:

範例2:

index.js


// Requiring module
import fs from "fs-extra";
  
// file and directory
//  does not  exist
// so both  will be created
// and data will be written
// onto the file
const file = "dir/file.txt";
  
// This data will be
// written onto file
const data = "This data will be written on file which doesn't exist";
  
// Additional options
const options = {
  encoding:"utf-8",
  flag:"w",
  mode:0o666,
};
  
// Function call
// Using Promises
fs.outputFile(file, data, options)
  .then(() => {
    console.log("File Written successfully");
    console.log("Content of file:");
    console.log(fs.readFileSync(file, "utf-8"));
  })
  .catch((e) => console.log(e));

輸出:

參考: https://github.com/jprichardson/node-fs-extra/blob/HEAD/docs/outputFile.md


相關用法


注:本文由純淨天空篩選整理自pritishnagpal大神的英文原創作品 Node.js fs-extra outputFile() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。