UNPKG

2.8 kBJavaScriptView Raw
1/**
2 * Tips
3 * ====
4 * - Set `user-agent` and `accept` headers when sending requests. Some services will not respond as expected without them.
5 * - Set `pool` to false if you send lots of requests using "request" library.
6 */
7
8var request = require('request')
9 , FeedParser = require(__dirname+'/..')
10 , Iconv = require('iconv').Iconv;
11
12function fetch(feed) {
13 // Define our streams
14 var req = request(feed, {timeout: 10000, pool: false});
15 req.setMaxListeners(50);
16 // Some feeds do not respond without user-agent and accept headers.
17 req.setHeader('user-agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36')
18 .setHeader('accept', 'text/html,application/xhtml+xml');
19
20 var feedparser = new FeedParser();
21
22 // Define our handlers
23 req.on('error', done);
24 req.on('response', function(res) {
25 if (res.statusCode != 200) return this.emit('error', new Error('Bad status code'));
26 var charset = getParams(res.headers['content-type'] || '').charset;
27 res = maybeTranslate(res, charset);
28 // And boom goes the dynamite
29 res.pipe(feedparser);
30 });
31
32 feedparser.on('error', done);
33 feedparser.on('end', done);
34 feedparser.on('readable', function() {
35 var post;
36 while (post = this.read()) {
37 console.log(post);
38 }
39 });
40}
41
42function maybeTranslate (res, charset) {
43 var iconv;
44 // Use iconv if its not utf8 already.
45 if (!iconv && charset && !/utf-*8/i.test(charset)) {
46 try {
47 iconv = new Iconv(charset, 'utf-8');
48 console.log('Converting from charset %s to utf-8', charset);
49 iconv.on('error', done);
50 // If we're using iconv, stream will be the output of iconv
51 // otherwise it will remain the output of request
52 res = res.pipe(iconv);
53 } catch(err) {
54 res.emit('error', err);
55 }
56 }
57 return res;
58}
59
60function getParams(str) {
61 var params = str.split(';').reduce(function (params, param) {
62 var parts = param.split('=').map(function (part) { return part.trim(); });
63 if (parts.length === 2) {
64 params[parts[0]] = parts[1];
65 }
66 return params;
67 }, {});
68 return params;
69}
70
71function done(err) {
72 if (err) {
73 console.log(err, err.stack);
74 return process.exit(1);
75 }
76 server.close();
77 process.exit();
78}
79
80// Don't worry about this. It's just a localhost file server so you can be
81// certain the "remote" feed is available when you run this example.
82var server = require('http').createServer(function (req, res) {
83 var stream = require('fs').createReadStream(require('path').resolve(__dirname, '../test/feeds' + req.url));
84 res.setHeader('Content-Type', 'text/xml; charset=Windows-1251');
85 stream.pipe(res);
86});
87server.listen(0, function () {
88 fetch('http://localhost:' + this.address().port + '/iconv.xml');
89});