fetch-langs.mjs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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(createReadStream(zipPath), unzipper.Extract({ path: destDir }));
  31. console.log('语言包解压完成!');
  32. // 删除临时压缩包
  33. fs.unlinkSync(zipPath);
  34. }
  35. // 示例调用
  36. const url =
  37. 'http://192.168.0.211:9012/v2/projects/export?ak=tgpak_gq2v62bymezha33wmzwg4yztobqwiy3dojxwy33che4wiyi';
  38. const dest = './src/locales/lang/json';
  39. await downloadAndExtract(url, dest);