Node.jsでファイルの拡張子を取得する3つの方法とそれぞれのメリット・デメリット
Node.jsでファイルの拡張子を取得する方法
path.parseを使う
Node.js標準のpath
モジュールを使うと、ファイルパスから拡張子を含むオブジェクトを取得できます。
const path = require('path');
const filePath = '/path/to/file.txt';
const parsedPath = path.parse(filePath);
const extension = parsedPath.ext;
console.log(extension); // '.txt'
ファイル名の文字列操作
ファイル名の末尾から拡張子を取り出す文字列操作を行う方法です。
const filePath = '/path/to/file.txt';
const extension = filePath.split('.').pop();
console.log(extension); // '.txt'
file-type
モジュールを使うと、ファイルの拡張子だけでなく、MIMEタイプなども取得できます。
const fileType = require('file-type');
const filePath = '/path/to/file.txt';
fileType.fromFile(filePath).then((fileType) => {
console.log(fileType.ext); // '.txt'
console.log(fileType.mime); // 'text/plain'
});
それぞれの方法のメリットとデメリット
- メリット:標準モジュールなのでインストール不要
- デメリット:拡張子以外のパーツも取得するため、処理が少し重くなる
- メリット:処理が軽い
- デメリット:ファイル名に拡張子が含まれていない場合、エラーが発生する
file-typeモジュールを使う
- メリット:拡張子だけでなく、MIMEタイプなども取得できる
Node.jsでファイルの拡張子を取得するには、上記のような方法があります。それぞれの方法のメリットとデメリットを理解して、状況に応じて使い分けてください。
const path = require('path');
const fileType = require('file-type');
const filePath = '/path/to/file.txt';
// path.parseを使う
const parsedPath = path.parse(filePath);
const extension1 = parsedPath.ext;
// ファイル名の文字列操作
const extension2 = filePath.split('.').pop();
// file-typeモジュールを使う
fileType.fromFile(filePath).then((fileType) => {
const extension3 = fileType.ext;
});
console.log(extension1); // '.txt'
console.log(extension2); // '.txt'
console.log(extension3); // '.txt'
このコードを実行すると、以下の出力が得られます。
.txt
.txt
.txt
応用例
ファイルの拡張子を取得する方法は、さまざまな場面で利用できます。例えば、以下のような用途があります。
- ファイルの種類を判別する
- ファイルのMIMEタイプを取得する
- ファイル名を変更する
他の方法
fs.statを使う
fs
モジュールのstat
関数をを使うと、ファイルのステータス情報を含むオブジェクトを取得できます。そのオブジェクトから拡張子を取得できます。
const fs = require('fs');
const filePath = '/path/to/file.txt';
fs.stat(filePath, (err, stats) => {
if (err) {
console.error(err);
return;
}
const extension = path.extname(stats.filename);
console.log(extension); // '.txt'
});
path.extnameを使う
path
モジュールのextname
関数は、ファイルパスから拡張子のみを抽出します。
const path = require('path');
const filePath = '/path/to/file.txt';
const extension = path.extname(filePath);
console.log(extension); // '.txt'
URLから拡張子を取得する
ブラウザでファイルを開く場合など、URLから拡張子を取得したいこともあります。その場合は、以下の方法があります。
const url = 'https://example.com/file.txt';
const extension = url.split('.').pop();
console.log(extension); // '.txt'
javascript node.js file-type