アプリケーションから指定されたポートへのアクセスや、オリジン間リソース共有(CORS)設定を検証する際、Dockerで仮想環境を立てるケースもあるかもしれません。
docker-composeで設定を都度書いていましたが、何か手軽な代替方法はないかと検索していたところ、http-serverの存在を知りました。
知っている人は当然のように使っているのかもしれません。今回は「なにそれ」という方向けに使い方を書いてみました。
インストール
予めnpmを導入しておきます。macOSであればHomeBrew経由でも可能です。
npm install -g http-server
brew install http-server
実行する
実行したディレクトリがベースとなります。受け付けるオプションは数豊富なので、目的に合わせて指定しましょう。
usage: http-server [path] [options]
options:
-p --port Port to use. If 0, look for open port. [8080]
-a Address to use [0.0.0.0]
-d Show directory listings [true]
-i Display autoIndex [true]
-g --gzip Serve gzip files when possible [false]
-b --brotli Serve brotli files when possible [false]
If both brotli and gzip are enabled, brotli takes precedence
-e --ext Default file extension if none supplied [none]
-s --silent Suppress log messages from output
--cors[=headers] Enable CORS via the "Access-Control-Allow-Origin" header
Optionally provide CORS headers list separated by commas
-o [path] Open browser window after starting the server.
Optionally provide a URL path to open the browser window to.
-c Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.
To disable caching, use -c-1.
-t Connections timeout in seconds [120], e.g. -t60 for 1 minute.
To disable timeout, use -t0
-U --utc Use UTC time format in log messages.
--log-ip Enable logging of the client's IP address
-P --proxy Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com
--proxy-options Pass options to proxy using nested dotted objects. e.g.: --proxy-options.secure false
--username Username for basic authentication [none]
Can also be specified with the env variable NODE_HTTP_SERVER_USERNAME
--password Password for basic authentication [none]
Can also be specified with the env variable NODE_HTTP_SERVER_PASSWORD
-S --tls --ssl Enable secure request serving with TLS/SSL (HTTPS)
-C --cert Path to TLS cert file (default: cert.pem)
-K --key Path to TLS key file (default: key.pem)
-r --robots Respond to /robots.txt [User-agent: *\nDisallow: /]
--no-dotfiles Do not show dotfiles
--mimetypes Path to a .types file for custom mimetype definition
-h --help Print this list and exit.
-v --version Print the version and exit.
ポート指定の場合は以下の通り。
http-server -p 8100
指定時間だけキャッシュさせての動作を見たい場合は以下の通りです。
http-server -c60
あとがき
普段npmのライブラリを使うことがなかったため、http-serverの手軽さは新鮮でした。
ポート指定やCORS動作確認、プロキシ指定での動作検証等、リクエスト時の各指定に関する手軽な動作検証には向いています。スクリプト動作検証等、本格的なサーバの動作確認を行いたい場合は他のライブラリを用いるべきでしょう。