Here's a complete solution that includes both client-side and server-side components to save a copy of the selected items text file to saves/<email_address>.txt:
📁 Project Folder Structure:
/catalog/
│
├── index.html
├── items.txt
├── server.js
├── package.json
├── saves/
│ └── (saved files will appear here)
└── images/
├── item1.jpg
├── item2.jpg
└── ... (more .jpg files)
💻 1. index.html (HTML + JavaScript):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Item Catalog</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
.item { border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; display: flex; gap: 20px; align-items: center; }
.item img { max-width: 150px; height: auto; }
.item-description { flex-grow: 1; }
input[type="email"] { width: 300px; padding: 5px; margin-bottom: 20px; }
button { padding: 10px 20px; font-size: 16px; }
</style>
</head>
<body>
<h1>Item Selection</h1>
<label for="email">Enter your email:</label><br>
<input type="email" id="email" placeholder="example@example.com" required><br><br>
<div id="items"></div>
<button onclick="downloadSelected()">Send</button>
<script>
async function loadItems() {
try {
const response = await fetch('items.txt');
const text = await response.text();
const lines = text.trim().split('\n');
const itemsContainer = document.getElementById('items');
lines.forEach((line, index) => {
const [filename, description] = line.split('|');
const itemDiv = document.createElement('div');
itemDiv.classList.add('item');
itemDiv.innerHTML = `
<img src="images/${filename}" alt="Item image">
<div class="item-description">
<p>${description}</p>
<label>
<input type="checkbox" class="item-checkbox" data-description="${description}">
Interested
</label>
</div>
`;
itemsContainer.appendChild(itemDiv);
});
} catch (err) {
console.error('Error loading items:', err);
}
}
async function downloadSelected() {
const email = document.getElementById('email').value;
const checkboxes = document.querySelectorAll('.item-checkbox:checked');
if (!email) {
alert('Please enter your email address.');
return;
}
if (checkboxes.length === 0) {
alert('Please select at least one item.');
return;
}
// Create content for the file
let message = `Thank you for your interest, ${email}!\n\nYou have selected the following items:\n\n`;
checkboxes.forEach(cb => {
message += `- ${cb.getAttribute('data-description')}\n`;
});
// Send data to the server
try {
const response = await fetch('/save', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, message }),
});
if (!response.ok) {
throw new Error('Failed to save data on the server');
}
// Create downloadable text file
const blob = new Blob([message], { type: 'text/plain' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'selected_items.txt';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
alert('Your selections have been saved and the file is ready to download.');
} catch (err) {
console.error('Error saving data:', err);
alert('There was an error saving your selections. Please try again.');
}
}
// Load items on page load
window.onload = loadItems;
</script>
</body>
</html>
💻 2. server.js (Node.js + Express):
const express = require('express');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;
// Middleware to parse JSON bodies
app.use(bodyParser.json());
// Serve static files from the current directory
app.use(express.static('.'));
// Ensure the saves directory exists
const savesDir = path.join(__dirname, 'saves');
if (!fs.existsSync(savesDir)) {
fs.mkdirSync(savesDir);
}
// Endpoint to save the data
app.post('/save', (req, res) => {
const { email, message } = req.body;
if (!email || !message) {
return res.status(400).send('Email and message are required');
}
// Sanitize the email to use as a filename
const sanitizedEmail = email.replace(/[^a-zA-Z0-9@._-]/g, '_');
const filename = path.join(savesDir, `${sanitizedEmail}.txt`);
// Write the message to the file
fs.writeFile(filename, message, (err) => {
if (err) {
console.error('Error saving file:', err);
return res.status(500).send('Error saving file');
}
res.send('Data saved successfully');
});
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
📄 3. package.json:
{
"name": "item-catalog",
"version": "1.0.0",
"description": "A simple item catalog with email and save functionality",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"dependencies": {
"express": "^4.17.1",
"body-parser": "^1.19.0"
}
}
🚀 How It Works:
-
Client-Side:
- Loads items from
items.txt and displays them with checkboxes.
- When the user clicks "Send", it sends the selected items and email to the server.
- Downloads a text file with the selected items.
-
Server-Side:
- Receives the email and message from the client.
- Sanitizes the email to create a valid filename.
- Saves the message to a file in the
saves/ directory with the email address as the filename.
-
Directory Structure:
- The
saves/ directory is created if it doesn't exist.
- Saved files are stored in this directory with the email address as the filename.
🔧 Running the Server:
- Install Node.js if you haven't already.
- Navigate to the directory containing
server.js and package.json.
- Run
npm install to install the dependencies.
- Run
npm start to start the server.
- Open your browser and navigate to
http://localhost:3000.
📝 Example items.txt:
item1.jpg|Red T-shirt, cotton, size M
item2.jpg|Wireless headphones with noise cancellation
item3.jpg|12" Non-stick frying pan
This solution ensures that the selected items are saved to the server while also allowing the user to download the file locally. The server-side component handles saving the file to the saves/ directory with the email address as the filename.