-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathapp.js
More file actions
83 lines (70 loc) · 2.44 KB
/
app.js
File metadata and controls
83 lines (70 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');
const path = require('path');
const app = express();
const PORT = 3001;
// Middleware to parse request bodies
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
// Route to serve the main page
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// API endpoint to fetch and modify content
app.post('/fetch', async (req, res) => {
try {
const { url } = req.body;
if (!url) {
return res.status(400).json({ error: 'URL is required' });
}
// Fetch the content from the provided URL
const response = await axios.get(url);
const html = response.data;
// Use cheerio to parse HTML and selectively replace text content, not URLs
const $ = cheerio.load(html);
// Function to replace text but skip URLs and attributes
function replaceYaleWithFale(i, el) {
if ($(el).children().length === 0 || $(el).text().trim() !== '') {
// Get the HTML content of the element
let content = $(el).html();
// Only process if it's a text node
if (content && $(el).children().length === 0) {
// Replace Yale with Fale in text content only
content = content.replace(/Yale/g, 'Fale').replace(/yale/g, 'fale');
$(el).html(content);
}
}
}
// Process text nodes in the body
$('body *').contents().filter(function() {
return this.nodeType === 3; // Text nodes only
}).each(function() {
// Replace text content but not in URLs or attributes
const text = $(this).text();
const newText = text.replace(/Yale/g, 'Fale').replace(/yale/g, 'fale');
if (text !== newText) {
$(this).replaceWith(newText);
}
});
// Process title separately
const title = $('title').text().replace(/Yale/g, 'Fale').replace(/yale/g, 'fale');
$('title').text(title);
return res.json({
success: true,
content: $.html(),
title: title,
originalUrl: url
});
} catch (error) {
console.error('Error fetching URL:', error.message);
return res.status(500).json({
error: `Failed to fetch content: ${error.message}`
});
}
});
// Start the server
app.listen(PORT, () => {
console.log(`Faleproxy server running at http://localhost:${PORT}`);
});