fs - Node.js

fs

fs モジュールは、Node.js のファイルを取り扱うモジュールです。

fs モジュールは、「 同期形式 」と「 非同期形式 」の両方が提供されています。

「synchronize(シンクロナイズ)」の頭文字をとっています。

synchronize : シンクロナイズ

同期させる

ファイルの作成

ファイルを作成する構文は、次のように記述します。

非同期通信

fs.writeFile('ファイルのパス', 'ファイルへ書きこむ内容', '文字コード', コールバック関数)

同期

fs.writeFileSync('ファイルのパス', 'ファイルへ書きこむ内容', '文字コード')

同一のファイル名が存在する場合は、ファイルの内容が上書きされます。

非同期通信

const fs = require('fs');

fs.writeFile('./test.txt', 'Hello, World', 'utf8', (err) => {
    if(err){
        console.log(err);
    } else {
        console.log('保存しました。');
    }
});

同期

const fs = require('fs');
fs.writeFileSync('./test.txt', "Hello, World", 'utf8');

ファイルへの追記

ファイルに追記する構文は、次のように記述します。

非同期

fs.appendFile(ファイルのパス, 追記したいデータ,  コールバック関数)

同期

fs.writeFileSync(ファイルのパス, 追記したいデータ)

非同期

const fs = require('fs');

fs.appendFile('./test.txt', 'Hello, World', (err) => {
    if(err){
        console.log(err);
    } else {
        console.log("ファイルに保存しました。");
    }
});

同期

const fs = require('fs');
fs.appendFileSync('./test.txt', 'Hello, World', 'utf8');

ファイルの読み込み

ファイルを読み込む構文は、次のように記述します。

非同期

fs.readFile(ファイルのパス, 文字コード,  コールバック関数)

同期

fs.readFileSync(ファイルのパス, 文字コード)

非同期

const fs = require('fs');

fs.readFile('./test.txt', 'utf8', (err, data) => {
    if(err){
        console.log(err);
    } else {
        console.log(data);
    }
});

同期

const fs = require('fs');
let data = fs.readFileSync('./test.txt', { encoding: 'utf8' });
console.log(data);

サンプル

const fs = require('fs');

function readFile(file){
    return new Promise((resolve, reject) => {
        fs.readFile(file, 'utf8', (err, data) => {
            if(err){
                reject(err);
            } else {
                resolve(data);
            }
        })
    })
}

readFile('./test.txt').then((data) => {
    console.log(data);
}).catch((err) => {
    console.error("エラー:" + err);
})

// ---------------------------------------------------------------------
const fs = require('fs');

fs.readFile("./tet.txt", 'utf8', (err, file)=> {
    return new Promise((resolve, reject) => {
        if(err){
            reject(err)
        } else {
            resolve(file)
        }
    }).then((data) => {
        console.log(data);
    }).catch((err) => {
        console.log("Error")
    })
})

ファイルの削除

ファイルを削除する構文は、次のように記述します。

非同期

fs.unlink(ファイルのパス, コールバック関数)

同期

fs.unlinkSync(ファイルのパス)
const fs = require('fs');

fs.unlink('./sample.txt', (err) => {
    if(err){
        console.log(err);
    } else {
        console.log("ファイルを削除しました。");
    }
});

指定されたファイルが存在しない場合は、例外が発生します。

同期

const fs = require('fs');

try{
    fs.unlinkSync('./sample.txt');
    console.log('削除しました。');
} catch(err) {
    console.log(err);
}

ファイルのリネーム

ファイルをリネームする構文は、次のように記述します。

非同期

fs.rename(before_file_Path, after_file_Path, コールバック関数);

同期

s.renameSync(before_file_Path, after_file_Path, コールバック関数);

ファイルの移動

rename または renameSync を使うとファイルの移動もできます。

fs.rename(beforePath, afterPath, err => {});

ファイルの移動 - 非同期

fs.rename('./images/sample.jpg', './destination/sample.jpg', (err) =>{
  // コールバック
})

ファイルの移動 - 同期

fs.renameSync('./images/sample.jpg', './destination/sample.jpg');

リネームしてのファイルの移動 - 非同期

fs.rename('./images/sample1.jpg', './destination/sample.jpg', (err) => {
  // コールバック
})

リネームしてのファイルの移動 - 同期

fs.renameSync('./images/sample1.jpg', './destination/sample.jpg');

ファイルのコピー

非同期

const fs = require("fs");
fs.copyFile("./test.txt","./test/test.txt", (err) => {
    if(err){
        console.log(err);
    } else {
        console.log("コピーが完了しました。");
    }
});

同期

const fs = require("fs");
fs.copyFileSync("./test.txt","./test/test.txt");