Node.jsでの圧縮入門
Node.jsとExpressで圧縮すると、ユーザーに提供されるダウンロード可能なデータ量が減少します。 この圧縮を使用することで、ペイロードサイズが大幅に削減されるため、Node.jsアプリケーションのパフォーマンスを向上させることができます。
圧縮には2つの方法があります。 1つは、compression
ミドルウェアを使用してNode.jsアプリで直接呼び出すことであり、もう1つは、NGINXなどのソフトウェアを介してリバースプロキシレベルで使用することです。
圧縮を設定する方法
Node.jsアプリケーションで圧縮の使用を開始するには、Node.jsアプリのメインファイルでcompression
ミドルウェアを使用できます。 これにより、さまざまな圧縮スキームをサポートするGZIPが有効になります。 これにより、JSON応答やその他の静的ファイル応答が小さくなります。
まず、compression
のnpmパッケージをインストールする必要があります。
$ npm i compression --save
次に、Express.jsのように、サーバーを初期化した後、アプリケーションでモジュールを使用できます。
const compression = require('compression'); const express = require('express'); const app = express(); // compress all responses app.use(compression()); app.get('/', (req, res) => { const animal = 'alligator'; // Send a text/html file back with the word 'alligator' repeated 1000 times res.send(animal.repeat(1000)); }); // ...
上記の例では、alligator
という単語が1000回印刷されたtext/html
ファイルを送り返すGET操作を呼び出します。 圧縮しないと、応答は約9kbのサイズで返されます。
圧縮をオンにすると、応答はContent-Encoding: gzip
を示すヘッダーで送信され、代わりに342Bのみになります。
圧縮のオプション
デフォルト設定に加えて、ユースケースに合わせて圧縮をカスタマイズできます。 オプションオブジェクトで使用できるいくつかの異なるプロパティがあります。 選択できるプロパティの完全なリストを取得するには、compression
ドキュメントを確認してください。
compression
のオプションを追加するには、コードは次のようになります。
const shouldCompress = (req, res) => { if (req.headers['x-no-compression']) { // don't compress responses if this request header is present return false; } // fallback to standard compression return compression.filter(req, res); }; app.use(compression({ // filter decides if the response should be compressed or not, // based on the `shouldCompress` function above filter: shouldCompress, // threshold is the byte threshold for the response body size // before compression is considered, the default is 1kb threshold: 0 }));
そして、あなたはそれを持っています! Node.jsアプリにcompression
を使用して、ペイロードサイズを小さくてスッキリと保つようにしてください。