StrongLoop / IBMによって提供されるこの翻訳.

本書は、英語の資料と比較すると古くなっている可能性があります。最新の更新については、英語版の資料を参照してください。

Express での静的ファイルの提供

イメージ、CSS ファイル、JavaScript ファイルなどの静的ファイルを提供するには、Express に標準実装されている express.static ミドルウェア関数を使用します。

The function signature is:

express.static(root, [options])

The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static.

For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:

app.use(express.static('public'))

これで、public ディレクトリーに入っているファイルをロードできます。

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
Express は、静的ディレクトリーから相対的なファイルを検索するため、静的ディレクトリーの名前は URL の一部ではありません。

複数の静的アセットディレクトリーを使用するには、express.static ミドルウェア関数を複数回呼び出します。

app.use(express.static('public'))
app.use(express.static('files'))

Express は、express.static ミドルウェア関数に静的ディレクトリーが設定された順序でファイルを検索します。

Note

For best results, use a reverse proxy cache to improve performance of serving static assets.

express.static 関数によって提供されるファイルの仮想パスのプレフィックス (パスは実際にはファイル・システムに存在しません) を作成するには、次に示すように、静的ディレクトリーのマウント・パスを指定します。

app.use('/static', express.static('public'))

これで、public ディレクトリー内のファイルを /static パス・プレフィックスからロードできます。

http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
http://localhost:3000/static/js/app.js
http://localhost:3000/static/images/bg.png
http://localhost:3000/static/hello.html

ただし、express.static 関数に指定するパスは、node プロセスを起動するディレクトリーに対して相対的です。別のディレクトリーから Express アプリケーションを実行する場合は、提供するディレクトリーの絶対パスを使用する方が安全です。 If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:

const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))

For more details about the serve-static function and its options, see serve-static.

Previous: Basic Routing     Next: More examples

Edit this page