8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.jsでssl証明書読み込みを判定してhttpとhttpsの切り分けをしてみる。

Last updated at Posted at 2014-07-17

express4系だとhttpモジュールの呼び出し部分が大分内部に入り込んでてアレだったので、今回のバージョンは3系です。

利用シーンですが

  • 本番環境 ssl対応
  • デプロイ環境 ssl非対応

という感じで本番のサーバーのみに証明書の情報があるときに使えると思います。

app.js
var http = require('http');
var https = require('https');
var fs = require('fs');

/*省略*/

  try {   
    var sslOptions = {
      key: fs.readFileSync('/path/to/ssl.key'),
      cert: fs.readFileSync('/path/to/ssl.cert'),
    };
	console.log('httpsで起動');
    var server = https.createServer(sslOptions, app);
  } catch (e) {
    console.log('ssl証明書読み込み失敗 httpで起動');
    var server = http.createServer(app);
  }
  
  server.listen(app.get('port'), function(res){
    if(constants.DEBUG)console.log("Express server listening on port " + app.get('port'));
  });

サーバーの情報などで振り分ける方法とかも考えられますけど, fs.readFileSync()のエラーハンドリングのテスト的な意味合いもあるのでとりあえずこれで実装しました。

参考: node.js - How to capture no file for fs.readFileSync()? - Stack Overflow

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?