Last active
May 9, 2023 01:38
-
-
Save mrhitman/365ba039902ce956307e5de1cb1df366 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const useragentFromSeed = require("useragent-from-seed"); | |
const axios = require("axios").default; | |
function getString(start, end, all) { | |
const regex = new RegExp(`${start}(.*?)${end}`); | |
const str = all; | |
const result = regex.exec(str); | |
return result[1]; | |
} | |
async function downloadTiktokVideo(url) { | |
const headers = { | |
authority: "www.tiktok.com", | |
"cache-control": "max-age=0", | |
"upgrade-insecure-requests": "1", | |
"user-agent": useragentFromSeed(), | |
accept: | |
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", | |
"sec-fetch-site": "none", | |
"sec-fetch-mode": "navigate", | |
"sec-fetch-user": "?1", | |
"sec-fetch-dest": "document", | |
"accept-language": "id-ID,id;q=0.9,en-US;q=0.8,en;q=0.7", | |
}; | |
const response = await axios.get(url, {headers}); | |
if (response.status !== 200) { | |
return null; | |
} | |
const script = getString( | |
'<script id="SIGI_STATE" type="application/json">', | |
"</script>", | |
response.data | |
); | |
if (script === null) { | |
return null; | |
} | |
const state = JSON.parse(script); | |
const videoUrl = state.ItemList.video.preloadList[0].url; | |
if (videoUrl === undefined) { | |
return null; | |
} | |
const writer = fs.createWriteStream("video.mp4"); | |
const videoStream = await axios.get(videoUrl, {responseType: "stream"}); | |
videoStream.data.pipe(writer); | |
return new Promise((res, rej) => { | |
let error; | |
writer.on("error", (err) => { | |
error = err; | |
rej(err); | |
}); | |
writer.on("close", () => { | |
if (!error) res(true); | |
}); | |
}); | |
} | |
const url = "https://www.tiktok.com/@kino_top20/video/7136618947327184134"; | |
downloadTiktokVideo(url); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment