UNPKG

tikinfo-api

Version:

Lightweight unofficial TikTok API for Node.js with zero dependencies

38 lines (30 loc) 1.09 kB
let fetchFn; try { fetchFn = globalThis.fetch || require("node-fetch"); } catch { throw new Error("Please install node-fetch for Node.js <18: npm i node-fetch"); } module.exports = class TikInfo { constructor() {} async getUser(username) { try { const res = await fetchFn(`https://www.tiktok.com/@${username}`, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" } }); if (!res.ok) { return { success: false, error: `Request failed with status ${res.status}` }; } const html = await res.text(); const match = html.match(/<script id="__UNIVERSAL_DATA_FOR_REHYDRATION__" type="application\/json">([\s\S]+?)<\/script>/); if (!match?.[1]) return { success: false, error: "User data not found in page" }; const data = JSON.parse(match[1]); const userInfo = data.__DEFAULT_SCOPE__?.["webapp.user-detail"]?.userInfo ?? null; if (!userInfo) return { success: false, error: "User not available" }; return { success: true, data: userInfo }; } catch (e) { return { success: false, error: e.message }; } } };