使用 Node.js 寫入檔案

寫入檔案

在 Node.js 中向檔案寫入的最簡單方法是使用 fs.writeFile() API。

const  = ('node:fs');

const  = 'Some content!';

.('/Users/joe/test.txt', ,  => {
  if () {
    .();
  } else {
    // file written successfully
  }
});

同步寫入檔案

或者,您可以使用同步版本 fs.writeFileSync()

const  = ('node:fs');

const  = 'Some content!';

try {
  .('/Users/joe/test.txt', );
  // file written successfully
} catch () {
  .();
}

您還可以使用 fs/promises 模組提供的基於 promise 的 fsPromises.writeFile() 方法

const  = ('node:fs/promises');

async function () {
  try {
    const  = 'Some content!';
    await .('/Users/joe/test.txt', );
  } catch () {
    .();
  }
}

();

預設情況下,如果檔案已存在,此 API 將替換檔案內容

您可以透過指定一個標誌來修改預設行為

fs.writeFile('/Users/joe/test.txt', content, { : 'a+' },  => {});

您可能會用到的標誌有

標誌描述如果檔案不存在則建立
r+此標誌開啟檔案用於讀取寫入
w+此標誌開啟檔案用於讀取寫入,並且它還將流定位在檔案的開頭
a此標誌開啟檔案用於寫入,並且它還將流定位在檔案的末尾
a+此標誌開啟檔案用於讀取寫入,並且它還將流定位在檔案的末尾
  • 您可以在 fs 文件中找到有關標誌的更多資訊。

向檔案追加內容

當您不想用新內容覆蓋檔案,而是想向其中新增內容時,追加到檔案非常方便。

示例

一個方便的將內容追加到檔案末尾的方法是 fs.appendFile()(以及其對應的 fs.appendFileSync()

const  = ('node:fs');

const  = 'Some content!';

.('file.log', ,  => {
  if () {
    .();
  } else {
    // done!
  }
});

使用 Promise 的示例

這是一個 fsPromises.appendFile() 的示例

const  = ('node:fs/promises');

async function () {
  try {
    const  = 'Some content!';
    await .('/Users/joe/test.txt', );
  } catch () {
    .();
  }
}

();