1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | var request = require('request')
|
9 | , FeedParser = require(__dirname+'/..')
|
10 | , Iconv = require('iconv').Iconv;
|
11 |
|
12 | function fetch(feed) {
|
13 |
|
14 | var req = request(feed, {timeout: 10000, pool: false});
|
15 | req.setMaxListeners(50);
|
16 |
|
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 |
|
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 |
|
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 |
|
42 | function maybeTranslate (res, charset) {
|
43 | var iconv;
|
44 |
|
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 |
|
51 |
|
52 | res = res.pipe(iconv);
|
53 | } catch(err) {
|
54 | res.emit('error', err);
|
55 | }
|
56 | }
|
57 | return res;
|
58 | }
|
59 |
|
60 | function 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 |
|
71 | function 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 |
|
81 |
|
82 | var 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 | });
|
87 | server.listen(0, function () {
|
88 | fetch('http://localhost:' + this.address().port + '/iconv.xml');
|
89 | });
|