import express from 'express';
import ytdl from 'ytdl-core';
import fs from 'fs';
import path from 'path';
import { v4 as uuidv4 } from 'uuid';
import { fileURLToPath } from 'url';
const router = express.Router();
// Defining dirname for ES module
const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);
// Validate the YouTube URL
if (!ytdl.validateURL(videoUrl)) {
return res.status(400).send({ msg: "Invalid YouTube URL." });
}
try {
// Get video info
console.log("Fetching video info for URL:", videoUrl);
const videoInfo = await ytdl.getInfo(videoUrl);
console.log("Video info retrieved successfully.");
const title = videoInfo.videoDetails.title.replace(/[/\\?%*:|"<>]/g, '');
const fileName = `${uuidv4()}-${title}.mp4`;
// Ensure a secure temporary directory (replace with your secure location)
const tempDir = path.join(__dirname, 'secure-tmp');
// Ensure temp directory exists
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir, { recursive: true });
}
const filePath = path.join(tempDir, fileName);
const videoStream = ytdl(videoUrl, {
filter: format => format.container === 'mp4',
requestOptions: {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
}
});
const writeStream = fs.createWriteStream(filePath);
// Pipe the video stream directly to the writeStream
videoStream.pipe(writeStream);
videoStream.on('error', (err) => {
console.error("Error streaming the video:", err);
return res.status(500).send({ msg: "Error processing the video." });
});
writeStream.on('finish', () => {
// Once file is written, send the file for download
res.download(filePath, `${title}.mp4`, (err) => {
if (err) {
console.error("Error during download:", err);
return res.status(500).send({ msg: "Error during download." });
}
// Cleanup the temp file
fs.unlink(filePath, (err) => {
if (err) {
console.error("Couldn't delete the file:", err);
}
});
});
});
writeStream.on('error', (err) => {
console.error("Error writing the file:", err);
res.status(500).send({ msg: "Error while writing the video." });
});
} catch (error) {
console.error("Error during video processing:", error);
// Check for 404 Not Found error and provide a specific message
if (error.statusCode === 404) {
res.status(404).send({ msg: "Video not found." });
} else {
res.status(500).send({ msg: "Problem with video processing." });
}
}
});
export default router;
Error Below: ->
erver is running on the port 3000
Fetching video info for URL: https://youtu.be/AjeijbFNDTI
Video info retrieved successfully.
Error streaming the video: MinigetError: Status code: 403
at ClientRequest. (/Users/satyamkumar/COHORT_0-1/project_01/server/node_modules/miniget/dist/index.js:206:27)
at Object.onceWrapper (node:events:629:26)
at ClientRequest.emit (node:events:514:28)
at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:693:27)
at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17)
at TLSSocket.socketOnData (node:_http_client:535:22)
at TLSSocket.emit (node:events:514:28)
at addChunk (node:internal/streams/readable:545:12)
at readableAddChunkPushByteMode (node:internal/streams/readable:495:3)
at Readable.push (node:internal/streams/readable:375:5) {
statusCode: 403
}
Based on the readme, this package is not longer maintained and @distube/ytdl-core is the recommended replacement
From a quick check, the issue is doesn't occur in @distube/ytdl-core
import express from 'express'; import ytdl from 'ytdl-core'; import fs from 'fs'; import path from 'path'; import { v4 as uuidv4 } from 'uuid'; import { fileURLToPath } from 'url';
const router = express.Router(); // Defining dirname for ES module const filename = fileURLToPath(import.meta.url); const dirname = path.dirname(filename);
router.route("/youtube/downloadVideos").post(async (req, res) => { const videoUrl = req.body.videoUrl;
});
export default router;
Error Below: -> erver is running on the port 3000 Fetching video info for URL: https://youtu.be/AjeijbFNDTI Video info retrieved successfully. Error streaming the video: MinigetError: Status code: 403 at ClientRequest. (/Users/satyamkumar/COHORT_0-1/project_01/server/node_modules/miniget/dist/index.js:206:27)
at Object.onceWrapper (node:events:629:26)
at ClientRequest.emit (node:events:514:28)
at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:693:27)
at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17)
at TLSSocket.socketOnData (node:_http_client:535:22)
at TLSSocket.emit (node:events:514:28)
at addChunk (node:internal/streams/readable:545:12)
at readableAddChunkPushByteMode (node:internal/streams/readable:495:3)
at Readable.push (node:internal/streams/readable:375:5) {
statusCode: 403
}