関数の概要
fs.promises.writeFileは、Node.jsのモジュールであるfsの一部であり、ファイルにデータを非同期で書き込むための関数です。主な目的は、ファイルを作成または上書きして、指定したデータを書き込むことです。
パラメータの説明
パラメータ | 型 | 用途 |
---|---|---|
file | string | 書き込み先のファイルパス |
data | string or Buffer | 書き込むデータ |
options | Object | オプション設定(例:エンコーディング) |
戻り値
Promiseオブジェクトを返します。非同期でファイル書き込みが完了した場合、resolveされ、エラーが発生した場合はrejectされます。
使用例
例1:ファイルにテキストデータを書き込む
const fs = require('fs').promises;
fs.writeFile('example.txt', 'Hello, World!')
.then(() => console.log('File written successfully'))
.catch((err) => console.error(err));
例2:ファイルにJSONデータを書き込む
const fs = require('fs').promises;
const data = { name: 'Alice', age: 30 };
fs.writeFile('data.json', JSON.stringify(data))
.then(() => console.log('JSON data written successfully'))
.catch((err) => console.error(err));
関連する関数
関連する関数:fs.promises.readFile、fs.promises.appendFile
まとめ
fs.promises.writeFileは、ファイルにデータを書き込むための便利な関数です。非同期で動作し、Promiseを扱うことでコールバックヘルを回避できます。ただし、エラー処理を適切に行うことが重要です。