-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (70 loc) · 1.95 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const { createWriteStream, mkdir } = require("fs");
const { clearLine, cursorTo } = require("readline");
const ytdl = require("ytdl-core");
const error_string =
"[YTDownload] ${error} \n\nFOR MORE ADVANCED HELP: https://338.rocks/discord";
/**
*
* @param {string} url
* @param {boolean} logging
* @returns {Promise<string>}
*/
const download = (url, logging = true) => {
return new Promise((resolve, reject) => {
mkdir("videos", (err) => {
if (err && err.code !== "EEXIST")
reject(error_string.replace(/${error}/gim, err.message));
ytdl.getInfo(url)
.then((info) => {
const video = ytdl(info.videoDetails.video_url);
const filePath = `./videos/${info.videoDetails.title.replace(
/[\W_]+/g,
" ",
)}.mp4`;
video.pipe(createWriteStream(filePath));
if (logging) {
console.time("[YTDownload] Downloaded in");
console.info(
`[YTDownload] Starting to download: ${info.videoDetails.title}`,
);
}
video.on("end", () => {
if (logging) {
console.info(
`\n[YTDownload] Download finished: ${info.videoDetails.title}`,
);
console.timeEnd("[YTDownload] Downloaded in");
console.log(
`[YTDownload] Downloaded to ${filePath}`,
);
}
resolve(filePath);
});
video.on("error", (error) =>
reject(
error_string.replace(/${error}/gim, error.message),
),
);
video.on("progress", (_, downloaded, total) => {
if (logging) {
const percent = (
(downloaded * 100) /
total
).toFixed(3);
clearLine(process.stdout, 0);
cursorTo(process.stdout, 0);
process.stdout.write(
`[YTDownload] Downloading ${percent}%`,
);
}
});
})
.catch((err) =>
reject(error_string.replace(/${error}/gim, err.message)),
);
});
});
};
module.exports = {
download,
};