Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const tiktok = require('@deiutr/tiktok-dl');
- const fs = require('fs').promises;
- const axios = require('axios');
- const process = require('process');
- const cliProgress = require('cli-progress');
- const METADATA_FILE_PREFIX = 'TikTokVideoMetadata';
- const VIDEO_FILE_PREFIX = 'TikTokVideo';
- const VIDEO_FILE_EXTENSION = '.mp4';
- (async () => {
- if (process.argv.length <= 2) {
- console.error('Usage: node downloadTikTok.js <TikTok Video URL>');
- process.exit(-1);
- }
- const videoUrl = process.argv[2];
- await downloadVideo(videoUrl);
- })();
- async function downloadVideo(url) {
- try {
- const videoInfo = await getVideoInfo(url);
- const directUrl = videoInfo.videoUrl;
- const videoMetadata = extractMetadata(videoInfo);
- await saveVideoMetadata(videoMetadata);
- await downloadAndSaveVideo(directUrl);
- } catch (error) {
- handleError(error);
- }
- }
- async function getVideoInfo(url) {
- const videoInfo = await tiktok.getInfo(url);
- if (!videoInfo || videoInfo.collector.length === 0) {
- throw new Error('Invalid video URL or video not found.');
- }
- return videoInfo.collector[0];
- }
- function extractMetadata(videoInfo) {
- return {
- title: videoInfo.text,
- author: videoInfo.authorMeta.name,
- description: videoInfo.description,
- createTime: videoInfo.createTime,
- };
- }
- async function saveVideoMetadata(metadata) {
- const fileName = `${METADATA_FILE_PREFIX}-${Date.now()}.json`;
- await fs.writeFile(fileName, JSON.stringify(metadata, null, 2));
- }
- async function downloadAndSaveVideo(url) {
- const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);
- progressBar.start(100, 0);
- console.log('Downloading video...');
- const response = await axios.get(url, { responseType: 'stream' });
- const totalLength = response.headers['content-length'];
- await saveVideoFile(response.data, totalLength, progressBar);
- }
- async function saveVideoFile(stream, totalLength, progressBar) {
- const outputFileName = `${VIDEO_FILE_PREFIX}-${Date.now()}${VIDEO_FILE_EXTENSION}`;
- const writer = fs.createWriteStream(outputFileName);
- stream.on('data', (chunk) => {
- progressBar.increment((chunk.length * 100) / totalLength);
- });
- stream.pipe(writer);
- return new Promise((resolve, reject) => {
- writer.on('finish', () => {
- progressBar.stop();
- console.log(`Download complete. File saved as ${outputFileName}`);
- resolve();
- });
- writer.on('error', (error) => {
- progressBar.stop();
- reject(error);
- });
- });
- }
- function handleError(error) {
- console.error('Error:', error.message);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement