voc-cli
Version:
download and play English vocabularies' audio via command line
104 lines (78 loc) • 2.58 kB
JavaScript
;
var _async_ = require('co').wrap;
var fetch = require('node-fetch');
var cheerio = require('cheerio');
var normalize = require('../lib/normalize');
var urlformat = require('url').format;
module.exports = _async_(regeneratorRuntime.mark(function _callee(word) {
var url, res, html, $, term, msg, err, set, list, _err;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
word = normalize(word);
url = 'https://tw.dictionary.search.yahoo.com/search' + urlformat({
query: {
fr2: 'dict',
p: word
}
});
_context.next = 4;
return fetch(url, { timeout: 10 * 1000 });
case 4:
res = _context.sent;
if (!(res.status !== 200)) {
_context.next = 7;
break;
}
throw new Error('request to ' + url + ' failed, status code = ' + res.status + ' (' + res.statusText + ')');
case 7:
_context.next = 9;
return res.text();
case 9:
html = _context.sent;
$ = cheerio.load(html);
// check the word from title
term = $('#term').text().trim().toLowerCase().replace(/·/g, '');
if (!(term !== word)) {
_context.next = 18;
break;
}
msg = '\'' + word + '\' is not found from yahoo';
if (term !== '') {
msg += '. Do you mean the word \'' + term + '\' ?';
}
err = new Error(msg);
err.code = 'ENOENT';
throw err;
case 18:
set = {};
JSON.parse($('#iconStyle.tri').text()).sound_url_1.forEach(function (item) {
if ('mp3' in item) {
set[item.mp3] = true;
}
});
list = Object.keys(set);
if (!(list.length === 0)) {
_context.next = 25;
break;
}
_err = new Error('\'' + word + '\' has no audio from yahoo');
_err.code = 'ENOENT';
throw _err;
case 25:
// show all the audio url
if (list.length > 1) {
list.forEach(function (audio, i) {
console.log(i + 1 + '. ' + audio);
});
}
// return the first audio from list
return _context.abrupt('return', list[0]);
case 27:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));