-
Notifications
You must be signed in to change notification settings - Fork 3
/
mouthful.js
52 lines (52 loc) · 1.33 KB
/
mouthful.js
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
const phantom = require('phantom');
const https = require('https');
const fs = require('fs');
const cheerio = require('cheerio');
const async = require('async');
const request = require('request');
const httpGet = (url, callback) => {
const options = {
url : url,
json : true
};
request(options,
function(err, res, body) {
callback(err, body);
}
);
}
const mouthful = async (url, callback) => {
const instance = await phantom.create();
const page = await instance.createPage();
let status = null;
let urls = [];
let stylesheet = '';
let inline = '';
let inlineCount = 0;
await page.on('onResourceRequested', (requestData) => {
if (requestData.headers[0].value.indexOf('text/css') !== -1) {
urls.push(requestData.url);
}
});
status = await page.open(url);
content = await page.property('content');
const $ = cheerio.load(content);
$('style').each((i, el) => {
inlineCount ++;
inline += $(el).html();
});
await instance.exit();
async.mapSeries(urls, httpGet, (err, res) => {
if (err) {
return console.log(err);
} else {
res.forEach((sheet) => {
stylesheet += sheet;
});
stylesheet += inline;
let _stylesheet = stylesheet.replace(/\n/g, '');
callback(_stylesheet, urls, inlineCount);
}
});
}
module.exports = mouthful;