Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mauriciomassaia/d766fd157b16c48d9cbe2af7ef56a44d to your computer and use it in GitHub Desktop.
Save mauriciomassaia/d766fd157b16c48d9cbe2af7ef56a44d to your computer and use it in GitHub Desktop.
Postinstall script to inject cacert.pem into Tinify dependency

When our team tried to use tinify into a AWS Lambda function using Typescript the file node_modules/tinify/lib/data/cacert.pem wasn't copied properly so the transpiled code could not find it and Tinify would fail.

Thanks to @shannonhochkins and his postinstall idea to inject the value of cacert.pem into Client.js.

How to setup this script

  1. Create a scripts/ folder on your project.
  2. Create a file called tinify-inject-cacertpem.js inside the scripts/ folder.
  3. Copy the contents from the file of this gist.
  4. Add a postinstall script into your package.json
{
  "scripts": {
    "postinstall": "node ./scripts/tinify-inject-cacertpem.js"
  }
}

With this script the cacert.pem will be injected into tinify/Client.js and it will not have issues when transpiting with Typescript.

const fs = require('fs');
const path = require('path');
// Check if node_modules exists
if (!fs.existsSync('node_modules')) {
console.error('node_modules does not exist');
process.exit(1);
}
// Check if tinify dependency exists
if (!fs.existsSync('node_modules/tinify')) {
console.error('tinify does not exist');
process.exit(1);
}
// Check if tinify/lib/data/cacert.pem exists
const certPath = 'node_modules/tinify/lib/data/cacert.pem';
if (!fs.existsSync(certPath)) {
console.error('cacert.pem does not exist');
process.exit(1);
}
// Check if tinify/lib/tinify/Client.js exists
const clientPath = 'node_modules/tinify/lib/tinify/Client.js';
if (!fs.existsSync(clientPath)) {
console.error('Client.js does not exist');
process.exit(1);
}
// Load cacert.pem into a string value
const certData = fs.readFileSync(certPath, 'utf8');
// Replace the line: const data = fs.readFileSync(`${__dirname}/../data/cacert.pem`).toString();
// with the cacert.pem string value
let clientData = fs.readFileSync(clientPath, 'utf8');
clientData = clientData.replace(/const data = fs\.readFileSync\(`\$\{__dirname\}\/\.\.\/data\/cacert\.pem`\)\.toString\(\);/g, `const data = \`${certData}\`;`);
// Save the file
fs.writeFileSync(clientPath, clientData);
console.log('Tinify transformed successfully! cacert.pem injected into Client.js');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment