TikTok Video Downloader

🧩 Syntax:
const tiktok = require('@deiutr/tiktok-dl');
const fs = require('fs');
const axios = require('axios').default;
const process = require('process');
const cliProgress = require('cli-progress');

// Make sure axios and cli-progress are installed:
// npm install axios cli-progress

// Check if the video URL is provided as a command-line argument
if (process.argv.length <= 2) {
    console.log('Usage: node downloadTikTok.js <TikTok Video URL>');
    process.exit(-1);
}

const videoUrl = process.argv[2];

// Function to download TikTok video
async function downloadVideo(url) {
    try {
        const videoInfo = await tiktok.getInfo(url);
        if (!videoInfo || videoInfo.collector.length === 0) {
            console.error('Invalid video URL or video not found.');
            return;
        }

        const directUrl = videoInfo.collector[0].videoUrl;
        const videoMetadata = {
            title: videoInfo.collector[0].text,
            author: videoInfo.collector[0].authorMeta.name,
            description: videoInfo.collector[0].description,
            createTime: videoInfo.collector[0].createTime,
        };

        // Save video metadata to a file
        saveVideoMetadata(videoMetadata);

        // Initialize and start progress bar
        const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic);
        progressBar.start(100, 0);

        console.log('Downloading video...');

        // Download video with progress tracking
        const response = await downloadWithProgress(directUrl, progressBar);

        // Save downloaded video to a file
        await saveVideoFile(response.data, progressBar);
    } catch (error) {
        handleError(error);
    }
}

// Function to save video metadata
function saveVideoMetadata(metadata) {
    fs.writeFileSync(`TikTokVideoMetadata-${Date.now()}.json`, JSON.stringify(metadata, null, 2));
}

// Function to handle video download with progress tracking
async function downloadWithProgress(url, progressBar) {
    return axios({
        method: 'get',
        url: url,
        responseType: 'stream',
        onDownloadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            progressBar.update(percentCompleted);
        },
    });
}

// Function to save the downloaded video file
function saveVideoFile(stream, progressBar) {
    const outputFileName = `TikTokVideo-${Date.now()}.mp4`;
    const writer = fs.createWriteStream(outputFileName);

    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', reject);
    });
}

// Function to handle errors
function handleError(error) {
    if (error.response) {
        console.error('Network error:', error.message);
    } else if (error.request) {
        console.error('The request was made but no response was received');
    } else {
        console.error('Error:', error.message);
    }
}

downloadVideo(videoUrl);
SwayZ

SwayZ

Member