NodeJS サーバーからファイルをダウンロードする方法(Express 使用)
NodeJS サーバーからファイルをダウンロードする方法(Express 使用)
準備
以下のものが必要です。
- NodeJS
- Express フレームワーク
- テキストエディタ
ファイル構造
以下のファイル構造を作成します。
my-app/
├── package.json
└── server.js
package.json
ファイルを作成し、以下の内容を追加します。
{
"name": "my-app",
"version": "1.0.0",
"description": "My application",
"main": "server.js",
"dependencies": {
"express": "^4.17.1"
}
}
const express = require('express');
const app = express();
app.get('/download', (req, res) => {
const file = `${__dirname}/file.txt`;
res.download(file);
});
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
このコードは、以下のことを行います。
- Express フレームワークをインポートします。
- Express アプリケーションを作成します。
/download
エンドポイントへの GET リクエストを処理します。file.txt
ファイルをダウンロードします。- サーバーをポート 3000 で起動します。
- サーバーを起動します。
node server.js
- ブラウザで
http://localhost:3000/download
にアクセスします。
ファイルがダウンロードされます。
オプション
filename
オプションを使用して、ダウンロードファイルの名前を指定できます。
res.download(file, { filename: 'my-file.txt' });
res.download(file, {
headers: {
'Content-Type': 'application/octet-stream'
}
});
このチュートリアルでは、Express フレームワークを使用して NodeJS サーバーからファイルをダウンロードする方法を説明しました。
const express = require('express');
const app = express();
// ダウンロードするファイルのパス
const filePath = `${__dirname}/file.txt`;
// `/download` エンドポイントへの GET リクエストを処理します
app.get('/download', (req, res) => {
// ファイル名を設定
const fileName = 'my-file.txt';
// ダウンロードファイルのヘッダーを設定
const headers = {
'Content-Type': 'application/octet-stream',
'Content-Disposition': `attachment; filename=${fileName}`
};
// ファイルをダウンロード
res.download(filePath, headers);
});
// サーバーをポート 3000 で起動
app.listen(3000, () => {
console.log('Server is listening on port 3000');
});
このコードを実行すると、ブラウザで http://localhost:3000/download
にアクセスすると、file.txt
ファイルが my-file.txt
という名前でダウンロードされます。
説明
filePath
変数は、ダウンロードするファイルのパスです。Content-Type
ヘッダーは、ダウンロードファイルの MIME タイプを設定します。
実行
- ターミナルで以下のコマンドを実行してサーバーを起動します。
node server.js
変更
- ダウンロードするファイルの名前や MIME タイプを変更できます。
- ダウンロードファイルのヘッダーを追加できます。
応用
このサンプルコードは、さまざまな目的に使用できます。
- ユーザーがファイルをダウンロードできるようにする
- ファイルを添付ファイルとして送信する
NodeJS サーバーからファイルをダウンロードする方法(その他の方法)
fs
モジュールを使用して、ファイルを直接読み込み、クライアントに送信できます。
const fs = require('fs');
app.get('/download', (req, res) => {
const file = `${__dirname}/file.txt`;
fs.readFile(file, (err, data) => {
if (err) {
res.status(500).send(err.message);
return;
}
res.setHeader('Content-Type', 'application/octet-stream');
res.send(data);
});
});
この方法は、小さなファイルや静的なファイルに適しています。
sendFile
モジュールを使用して、ファイルを簡単に送信できます。
const sendFile = require('send-file');
app.get('/download', (req, res) => {
const file = `${__dirname}/file.txt`;
sendFile(res, file, (err) => {
if (err) {
res.status(500).send(err.message);
return;
}
});
});
第三者ライブラリを使用する
multer
や busboy
などの第三者ライブラリを使用して、ファイルをアップロードしたりダウンロードしたりできます。
これらのライブラリは、ファイル処理をより簡単に、より強力にする多くの機能を提供します。
NodeJS サーバーからファイルをダウンロードするには、さまざまな方法があります。
最適な方法は、要件と使用例によって異なります。
javascript node.js file