fetch-langs.mjs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import fetch from "node-fetch";
  2. import fs from "fs";
  3. import path from "path";
  4. import unzipper from "unzipper";
  5. import { pipeline } from "node:stream";
  6. import { promisify } from "node:util";
  7. import { createReadStream, createWriteStream } from "node:fs";
  8. const streamPipeline = promisify(pipeline);
  9. /**
  10. * 下载并解压离线包
  11. * @param {string} url 下载地址
  12. * @param {string} destDir 解压目标目录
  13. */
  14. async function downloadAndExtract(url, destDir) {
  15. const zipPath = path.join(destDir, "temp.zip");
  16. console.log(`开始下载语言包: ${url}`);
  17. const res = await fetch(url, {
  18. method: "GET",
  19. headers: {
  20. //'X-API-Key':'tgpak_gm2f6ntnor2gy4ztnfuw65twoj2wu2tdovzwwztqoe4ts5q'
  21. },
  22. });
  23. if (!res.ok) {
  24. throw new Error(`下载语言包失败: ${res.status} ${res.statusText}`);
  25. }
  26. // zip文件保存到本地目录
  27. await streamPipeline(res.body, createWriteStream(zipPath));
  28. console.log("语言包下载完成,开始解压...");
  29. // 解压到指定目录
  30. await streamPipeline(
  31. createReadStream(zipPath),
  32. unzipper.Extract({ path: destDir })
  33. );
  34. console.log("语言包解压完成!");
  35. // 删除临时压缩包
  36. fs.unlinkSync(zipPath);
  37. }
  38. // 示例调用
  39. const url =
  40. "http://192.168.0.211:9012/v2/projects/export?ak=tgpak_gqyv6y3ngbrtg2dtg5xw65llnazxim3bgnxwwodvmizhcny";
  41. const dest = "./src/lang/locales";
  42. await downloadAndExtract(url, dest);