-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
56 lines (50 loc) · 1.71 KB
/
index.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
53
54
55
56
const fs = require("fs");
const ytdl = require("ytdl-core");
const readline = require("readline");
const path = require("path");
const homedir = require("os").homedir();
const stream = require("./stream");
const download = (url, title) => {
let folder = "playtSongs";
const output = path.resolve(homedir, `./${folder}/${title}.m4a`);
let dir = `${homedir}/${folder}`;
if (!fs.existsSync(dir)) {
fs.mkdirSync(path.join(homedir, folder));
}
const video = ytdl(url, { filter: "audioonly" });
video.pipe(fs.createWriteStream(output));
let starttime;
// streams the song
stream(url);
console.log(`Streaming...`);
// starts timer once download is started
video.once("response", () => {
starttime = Date.now();
});
// keeps track of download progress
video.on("progress", (chunkLength, downloaded, total) => {
const percent = downloaded / total;
const downloadedMinutes = (Date.now() - starttime) / 1000 / 60;
readline.cursorTo(process.stdout, 0);
process.stdout.write(`${(percent * 100).toFixed(2)}% downloaded `);
process.stdout.write(
`(${(downloaded / 1024 / 1024).toFixed(2)}MB of ${(
total /
1024 /
1024
).toFixed(2)}MB)\n`
);
// writes download progress to the console
process.stdout.write(
`estimated download time left: ${(
downloadedMinutes / percent -
downloadedMinutes
).toFixed(2)}minutes `
);
readline.moveCursor(process.stdout, 0, -1);
});
video.on("end", () => {
process.stdout.write("\n\n");
});
};
module.exports = download;