MCPcopy
hub / github.com/ZToolsCenter/ZTools / downloadFile

Function downloadFile

src/main/utils/download.ts:22–171  ·  view source on GitHub ↗
(
  url: string,
  filePath: string,
  options: DownloadFileOptions = {}
)

Source from the content-addressed store, hash-verified

20}
21
22export async function downloadFile(
23 url: string,
24 filePath: string,
25 options: DownloadFileOptions = {}
26): Promise<void> {
27 return new Promise<void>((resolve, reject) => {
28 if (options.signal?.aborted) {
29 reject(new DownloadCancelledError())
30 return
31 }
32
33 let settled = false
34 let writeStream: ReturnType<typeof createWriteStream> | null = null
35 const request = net.request({
36 url,
37 session: session.defaultSession // 显式指定使用 defaultSession(确保代理配置生效)
38 })
39
40 const cleanup = (): void => {
41 options.signal?.removeEventListener('abort', handleAbort)
42 }
43
44 const finish = (callback: () => void): void => {
45 if (settled) return
46 settled = true
47 cleanup()
48 callback()
49 }
50
51 const fail = (err: unknown): void => {
52 finish(() => {
53 try {
54 request.abort()
55 } catch {
56 // 忽略失败清理时的请求状态差异
57 }
58 writeStream?.destroy()
59 reject(err)
60 })
61 }
62
63 function handleAbort(): void {
64 try {
65 request.abort()
66 } catch {
67 // 忽略 abort 期间的底层请求状态差异
68 }
69 fail(new DownloadCancelledError())
70 }
71
72 options.signal?.addEventListener('abort', handleAbort, { once: true })
73
74 // 禁用缓存的请求头(确保每次都下载最新文件)
75 request.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
76 request.setHeader('Pragma', 'no-cache')
77 request.setHeader('Expires', '0')
78
79 request.setHeader(

Callers 4

checkUpdateMethod · 0.85
installPluginFromNpmMethod · 0.85

Calls 3

failFunction · 0.85
onMethod · 0.80
finishFunction · 0.70

Tested by

no test coverage detected