This guide will help you create a Node.js script that generates a Gravatar URL based on an email address using the SHA-256 hashing algorithm. This is useful for server-side processing or script-based tasks.
Prerequisites
- Node.js installed on your machine.
- Familiarity with running Node.js scripts.
Step 1: Install Dependencies
Install the crypto
library (for SHA-256 hashing) using npm:
npm install crypto
Step 2: Set Up Your Node.js Script
Create a new file named generate-gravatar.js
.
Step 3: Script to Generate Gravatar URL
In your generate-gravatar.js
, import the crypto
library and define the functions to compute the Gravatar URL:
const crypto = require('crypto');
function getGravatarUrl(email, size = 80) {
const trimmedEmail = email.trim().toLowerCase();
const hash = crypto.createHash('sha256').update(trimmedEmail).digest('hex');
return `https://www.gravatar.com/avatar/${hash}?s=${size}&d=identicon`;
}
// Example usage
const email = 'your-email@example.com';
const size = 200; // Optional size parameter
const gravatarUrl = getGravatarUrl(email, size);
console.log('Gravatar URL:', gravatarUrl);
Step 4: Run the Script
Run your script via the command line to see the output:
node generate-gravatar.js
This command will print the Gravatar URL for the email specified in the script. You can change the email or size to test with different parameters.