Создайте приложение на Node.js, которое принимает URL в качестве аргумента командной строки, загружает HTML-контент по указанному URL, подсчитывает количество тегов на странице и сохраняет результат в tags.json.
• node app.js report https://example.com
— сохраняет количество тегов HTML-страницы в файл tags.json.
• node app.js print https://example.com
— выводит статистику по тегам на странице в консоль.
Решение задачи
const https = require('https');
const fs = require('fs');
const { JSDOM } = require('jsdom');
const action = process.argv[2];
const url = process.argv[3];
function fetchHtml(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
let data = '';
res.on('data', (chunk) => (data += chunk));
res.on('end', () => resolve(data));
}).on('error', (err) => reject(err));
});
}
async function report(url) {
try {
const html = await fetchHtml(url);
const dom = new JSDOM(html);
const tags = Array.from(dom.window.document.getElementsByTagName('*')).map(el => el.tagName);
const tagCount = tags.reduce((acc, tag) => {
acc[tag] = (acc[tag] || 0) + 1;
return acc;
}, {});
fs.writeFileSync('tags.json', JSON.stringify(tagCount, null, 2));
console.log('Статистика сохранена в tags.json');
} catch (err) {
console.error('Ошибка:', err);
}
}
async function print(url) {
try {
const html = await fetchHtml(url);
const dom = new JSDOM(html);
const tags = Array.from(dom.window.document.getElementsByTagName('*')).map(el => el.tagName);
const tagCount = tags.reduce((acc, tag) => {
acc[tag] = (acc[tag] || 0) + 1;
return acc;
}, {});
console.log('Статистика по тегам:', tagCount);
} catch (err) {
console.error('Ошибка:', err);
}
}
if (action === 'report') {
report(url);
} else if (action === 'print') {
print(url);
} else {
console.log('Используйте команды: report <URL> или print <URL>');
}