-
Notifications
You must be signed in to change notification settings - Fork 0
/
getLyrics.js
40 lines (30 loc) · 972 Bytes
/
getLyrics.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
const fetch = require('node-fetch');
const cheerio = require('cheerio');
async function getLyrics(song, artist) {
const url = await getSongUrl(song, artist);
const lyrics = await scrapeLyrics(url);
return lyrics;
}
module.exports = getLyrics;
async function getSongUrl(song, artist) {
const res = await fetch(`https://api.genius.com/search?q=${song.trim()} ${artist.trim()}`, {
headers: {
"Content-type": "application/json:",
"Authorization": `Bearer ${process.env.API_KEY}`
},
});
const { response } = await res.json();
const { hits } = response;
for (let hit of hits) {
if (hit.result.primary_artist.name.toLowerCase() === artist.toLowerCase()) {
return hit.result.url;
}
}
throw new Error('Artist Name MisMatched');
}
async function scrapeLyrics(url) {
const response = await fetch(url);
const text = await response.text();
const $ = cheerio.load(text);
return $('.lyrics').text().trim();
}