forked from sindresorhus/fast-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
54 lines (46 loc) · 1.57 KB
/
api.js
File metadata and controls
54 lines (46 loc) · 1.57 KB
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
53
54
'use strict';
/* eslint-env browser */
const puppeteer = require('puppeteer');
const Observable = require('zen-observable');
const equals = require('deep-equal'); // TODO: Use `util.isDeepStrictEqual` when targeting Node.js 10
const delay = require('delay');
async function init(browser, page, observer, options) {
let prevResult;
/* eslint-disable no-constant-condition, no-await-in-loop */
while (true) {
const result = await page.evaluate(() => {
const $ = document.querySelector.bind(document);
return {
downloadSpeed: Number($('#speed-value').textContent),
uploadSpeed: Number($('#upload-value').textContent),
downloadUnit: $('#speed-units').textContent.trim(),
uploadUnit: $('#upload-units').textContent.trim(),
isDone: Boolean(
$('#speed-value.succeeded') && $('#upload-value.succeeded')
)
};
});
if (result.downloadSpeed > 0 && !equals(result, prevResult)) {
observer.next(result);
}
if (result.isDone || (options && !options.measureUpload && result.uploadSpeed)) {
browser.close();
observer.complete();
return;
}
prevResult = result;
await delay(100);
}
/* eslint-enable no-constant-condition, no-await-in-loop */
}
module.exports = options => (
new Observable(observer => {
// Wrapped in async IIFE as `new Observable` can't handle async function
(async () => {
const browser = await puppeteer.launch({args: ['--no-sandbox']});
const page = await browser.newPage();
await page.goto('https://fast.com');
await init(browser, page, observer, options);
})().catch(observer.error.bind(observer));
})
);