fs-extra 中的 outputFile() 函式 - NodeJS


非同步 outputFile() 函式簡介

此方法類似於 'fs' 的寫入檔案方法。唯一的區別在於,如果父目錄不存在,它將建立父目錄。傳遞的引數始終應為檔案路徑,而不是緩衝區或檔案描述符。

語法

outputFile(file, data[, options] [, callback])

引數

  • file – 字串引數,包含檔案的名稱和位置。

  • data – 資料可以儲存字串資料、緩衝區流或要儲存的 Unit8 字串陣列。

  • options – 'outputFile' 函式支援以下選項:

    • encoding – 預設值 'utf8'。

    • mode – 預設值 0o666

    • signal – 允許中止正在進行的輸出檔案函式

  • callback – 如果發生任何錯誤,此函式將提供回撥。

示例

  • 在繼續之前,請檢查是否已安裝 fs-extra;如果未安裝,請安裝 fs-extra。

  • 您可以使用以下命令檢查是否已安裝 fs-extra。

npm ls fs-extra
  • 建立一個 asyncOutputFile.js 檔案,並將以下程式碼片段複製貼上到該檔案中。

  • 現在,執行以下命令以執行以下程式碼片段。

node asyncOutputFile.js

程式碼片段

const fs = require('fs-extra')

const file = '/tmp/not/exist/file.txt'

// Writing file with a callback:
fs.outputFile(file, 'Welcome to Tutorials Point!', err => {
   console.log(err) // => null

   fs.readFile(file, 'utf8', (err, data) => {
      if (err) return console.error(err)
      console.log(data) // => Welcome to Tutorials Point!
   })
})

// Writing file with Promises:
fs.outputFile(file, 'Welcome to Tutorials Point!')
.then(() => fs.readFile(file, 'utf8'))
.then(data => {
   console.log(data) // => Welcome to Tutorials Point!
})
.catch(err => {
   console.error(err)
})

// Writing file async/await:
async function asyncOutputFileExample (f) {
   try {
      await fs.outputFile(f, 'Welcome to Tutorials Point!')
      const data = await fs.readFile(f, 'utf8')
      console.log(data) // => Welcome to Tutorials Point!
   } catch (err) {
      console.error(err)
   }
}

asyncOutputFileExample(file)

輸出

C:\Users\tutorialsPoint\> node asyncOutputFile.js
null
Welcome to Tutorials Point!
Welcome to Tutorials Point!
Welcome to Tutorials Point!

outputFileSync() 函式簡介

此方法與 'fs' 中的 writeFileSync 方法相同。唯一的區別在於,如果父目錄不存在,它將建立父目錄。傳遞的引數始終應為檔案路徑,而不是緩衝區或檔案描述符。

語法

outputFileSync(file, data[, options])

引數

  • file – 這是一個字串引數,將儲存檔案的位置。

  • data – 資料可以儲存字串資料、緩衝區流或要儲存的 Unit8 字串陣列。

  • options – 'outputFile' 函式支援以下選項:

    • encoding – 預設值 'utf8'。

    • mode – 預設值 0o666

    • flag – 檔案操作的不同標誌選項

示例

  • 在繼續之前,請檢查是否已安裝 fs-extra;如果未安裝,請安裝 fs-extra。

  • 您可以使用以下命令檢查是否已安裝 fs-extra。

npm ls fs-extra
  • 建立一個 outputFileSyncExample.js 檔案,並將以下程式碼片段複製貼上到該檔案中。

  • 現在,執行以下命令以執行以下程式碼片段。

node outputFileSyncExample.js

程式碼片段

const fs = require('fs-extra')

const file = '/tmp/this/path/does/not/exist/file.txt'
fs.outputFileSync(file, 'Welcome to Tutorials Point!')

const data = fs.readFileSync(file, 'utf8')
console.log(data) // => Welcome to Tutorials Point!

輸出

C:\Users\tutorialsPoint\> node outputFileSyncExample.js
Welcome to Tutorials Point!

更新於:2021-04-28

335 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告