関連

プロミス化

utilモジュールのpromisifyでラップすることでPromise関数化できます。

const {promisify} = require('util');
const {readFile} = require('fs');

const readFilePromise = promisify(readFile);

readFile

あるディレクトリ上にあるファイルやディレクトリ名の一覧を取得します。

fs.readFile('./package.json', 'utf-8', (err, content) => {
  if (err === null) {
    // `Error: EISDIR: illegal operation on a directory` など
  }
  
  console.log(content);
  // {"name": "...", ...}
}

画像などを読み込む時は、utf-8指定はいりません。

fs.readFile('./static/logo.png', (err, content) => {
  // ...
}

readdir

あるディレクトリ上にあるファイルやディレクトリ名の一覧を取得します。

fs.readdir('.', (err, list) => {
  if (err === null) {
    // `Error: ENOENT: no such file or directory` など
  }
  
  console.log(list);
  // [
  //   '.git',
  //   ...
  //   'yarn.lock'
  // ]
}

JavaScript で飯食べたい歴約 8 年、 純( nju33 ) によるノートサイトです。

このサイトではドリンク代や奨学金返済の為、広告などを貼らせて頂いてますがご了承ください。

Change Log