const fs = require('fs');
const request = require('request');
const htmlparser = require('htmlparser');
const configFilename = './rss_feeds.txt';
function checkForRSSFile() { //Задача #1: Убедиться в том, что RSS существует.
fs.exists(configFilename, (exists) => {
if (!exists)
return next(new Error(`Missing RSS file: ${configFilename}`)); //При возникновении ошибки вернуть управление
next(null, configFilename);
});
}
function readRSSFile(configFilename) { //Задача #2: Прочитать RSS файл.
fs.readFile(configFilename, (err, feedlist) => {
if(err) return next(err);
feedlist = feedlist
.toString() //Привести в стринг.
.replace(/^\s+|\s+$/g) //Не понятно.
.split('\n');
const random = Math.floor(Math.random() * feedlist.lenght) //Выбирает случайный URL из массива.
next(null, feedlist[random]);
});
}
function downloadRSSFeed(feedUrl) { // Выполнить запрос HTTP, а после получить данные выбранного канала.
request({uri: feedUrl}, (err, res, body) => {
if (err) return next(err);
if(res.statusCode !== 200)
return next(new Error('Abnormal response status code.')); //Если ошибка при запросе.
next(null, body);
})
}
function parseRSSFeed(rss) { //Разбирать данные RSS в Массив.
const handler = new htmlparser.RssHandler() //?
const parser = new htmlparser.Parser(handler); //?
parser.parseComplete(rss);
if(!handler.dom.items.lenght) //Если RSS данных нету.
return next(new Error('No Rss items found.'));
const item = handler.dom.items.shift(); //?
console.log(item.title);
console.log(item.link);
}
const tasks = [ //Порядок выполнения задач
checkForRSSFile, //1
readRSSFile, //2
downloadRSSFeed, //3
parseRSSFeed //4
];
function next(err, result) { //Выполняет задачи.
if(err) throw err; //Исключение.
const currentTask = tasks.shift(); //Берет следующую задачу из массива задач.
if(currentTask) {
currentTask(result); //Выполняет текущую задачу.
}
}
next();
if(err) throw err; //Исключение.
^
Error: options.uri is a required argument
at Request.init (/Users/oxxxra/hello_express/listing_217/node_modules/request/request.js:244:31)
at new Request (/Users/oxxxra/hello_express/listing_217/node_modules/request/request.js:140:8)
at request (/Users/oxxxra/hello_express/listing_217/node_modules/request/index.js:55:10)
at downloadRSSFeed (/Users/oxxxra/hello_express/listing_217/index.js:25:3)
at next (/Users/oxxxra/hello_express/listing_217/index.js:53:5)
at fs.readFile (/Users/oxxxra/hello_express/listing_217/index.js:21:5)
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)
В чем моя ошибка?
Выделенный сервер, что это, для чего нужен и какие характеристики важны?
Современные решения для бизнеса: как облачные и виртуальные технологии меняют рынок
Виртуальный выделенный сервер (VDS) становится отличным выбором
Хочу познать суть) в общем есть кучаВ си это динамическая область памяти, где аллоцируются объекты через new (говорю о ++)
Помогите, пожалуйста, вывести результат js-функции (sum) в окне вывода по щелчку кнопки
Может вот это ? Кликните на зеленый блок чтобы подвинуть его
Уточните как в JS вывести в лог не весь массив от события а определенную переменную: