logo

ノード JS fs.writeFile() メソッド

fs.writeFile() メソッド 指定されたデータをファイルに非同期的に書き込むために使用されます。デフォルトでは、ファイルが存在する場合は置き換えられます。 「options」パラメータを使用して、メソッドの機能を変更できます。

構文:



fs.writeFile( file, data, options, callback )>

パラメーター:

リンクリストJava

このメソッドは、上で説明し、以下で説明する 4 つのパラメーターを受け入れます。

  • ファイル: これは、書き込む必要があるファイルのパスを示す文字列、バッファ、URL、またはファイル説明の整数です。ファイル記述子を使用すると、fs.write() メソッドと同様に動作します。
  • データ: ファイルに書き込まれるのは文字列、Buffer、TypedArray、または DataView です。
  • オプション: これは、出力に影響を与えるオプションのパラメーターを指定するために使用できる文字列またはオブジェクトです。これには 3 つのオプションのパラメータがあります。
    • エンコーディング: ファイルのエンコーディングを指定する文字列値です。デフォルト値は「utf8」です。
    • モード: ファイルモードを指定する整数値です。デフォルト値は 0o666 です。
    • フラグ: これは、ファイルへの書き込み中に使用されるフラグを指定する文字列値です。デフォルト値は「w」です。
  • 折り返し電話: これは、メソッドの実行時に呼び出される関数です。
    • エラー: これは、操作が失敗した場合にスローされるエラーです。

ノード JS アプリケーションを作成する手順:

ステップ1: ノードプロジェクトフォルダーを作成し、ローカルにインストールします。 npm init -y



npm init -y>

ステップ2: プロジェクトフォルダーを作成したら、次のコマンドを使用してプロジェクトフォルダーに移動します。

cd *project folder name*>

プロジェクトの構造:

ノードプロジェクト

プロジェクトの構造



例 1: 以下の例は、 fs.writeFile() メソッド Node.js で:

JavaScript


Python プログラムの例



// Node.js program to demonstrate the> // fs.writeFile() method> // Import the filesystem module> const fs = require(>'fs'>);> let data = 'This is a file containing a collection of books.';> fs.writeFile('books.txt', data, (err) =>{> >if> (err)> >console.log(err);> >else> {> >console.log('File written successfully ');> >console.log('The written has the following contents:');> >console.log(fs.readFileSync('books.txt', 'utf8'));> >}> });>

>

>

bash 文字列の長さ

出力:

File written successfully The written has the following contents: This is a file containing a collection of books.>

例 2: 以下の例は、 fs.writeFile() メソッド Node.js で:

JavaScript




// Node.js program to demonstrate the> // fs.writeFile() method> // Import the filesystem module> const fs = require(>'fs'>);> let data = 'This is a file containing a collection of movies.';> fs.writeFile('movies.txt', data,> >{> >encoding: 'utf8',> >flag: 'w',> >mode: 0o666> >},> >(err) =>{> >if> (err)> >console.log(err);> >else> {> >console.log('File written successfully ');> >console.log('The written has the following contents:');> >console.log(fs.readFileSync('movies.txt', 'utf8'));> >}> });>

mysqlワークベンチの使い方
>

>

出力:

File written successfully The written has the following contents: This is a file containing a collection of movies.>