現状
長らく放置していたnode(version8くらい)で作ったイメージをリサイズするLambdaが死んでいたので修正していた。
死ぬようになった原因は、Lambdaを実行するイメージのベースがAmazonLinux2に移行してimagemagickがデフォルトで含まれなくなったせいなので、最初は imagemagick を入れ直そうと思った。
けど、Lambdaレイヤー入れるとか話が大きくなるし、実際試してみたらうまくいかなかったので、CloudFrontのLambda@edgeの例で使われている sharp に入れ変えるために試行錯誤した。
Lambdaの修正
先に修正例から。画像をリサイズするコードをimagemagickで書いた例。
const im = require('imagemagick'); const img = await new Promise((resolve, reject) => { im.resize({ srcData: obj.Body, format: extension, height: 200 }, function (err, stdout, stderr) { if (err) { reject(err) } else { resolve({ ct: contentType, output: stdout }) } }); });
上記コードを sharpで書いた例。
const sharp = require('sharp'); const img = await sharp(obj.Body).resize({ width: 200 }).toBuffer();
Promiseの有り無しがあるけれど大体同じ感じ。コードが簡単に入れ替えられるならこれで良さそう。
インストール
インストールはいつも通りコマンドで一発
npm i sharp
いざソースを上げてみるとエラーが出る。
Could not load the "sharp" module using the linux-x64 runtime
Possible solutions:
- Ensure optional dependencies can be installed:
npm install --include=optional sharp
yarn add sharp --ignore-engines
- Ensure your package manager supports multi-platform installation:
See https://sharp.pixelplumbing.com/install#cross-platform
- Add platform-specific dependencies:
npm install --os=linux --cpu=x64 sharp
- Consult the installation documentation:
See https://sharp.pixelplumbing.com/install
"Could not load the \"sharp\" module using the linux-x64 runtime
ERR_DLOPEN_FAILED: libvips-cpp.so.42: cannot open shared object file: No such file or directory\nPossible solutions:
- Ensure optional dependencies can be installed:
npm install --include=optional sharp
yarn add sharp --ignore-engines
- Ensure your package manager supports multi-platform installation:
See https://sharp.pixelplumbing.com/install#cross-platform
- Add platform-specific dependencies:
npm install --os=linux --cpu=x64 sharp
- Consult the installation documentation:
See https://sharp.pixelplumbing.com/install",
メッセージを見るにプラットフォームごとのライブラリが入っていないと言うのがわかる。上記エラーメッセージにも npm install --os=linux --cpu=x64 sharp を実行してプラットフォームのライブラリをインストールしろと書いてある。でも実行してもうまくいかない。
最終的に下記のようにインストールしたらうまくいった。
npm i @img/sharp-linux-x64 npm i @img/sharp-libvips-linux-x64
プラットフォーム固有のインストールをpackage.jsonに書くのはよろしくない気はするが、Lambdaしか使わないのでこれでよしとする。
まとめ
EOLまで放置するな。