MCPcopy Create free account
hub / github.com/ZToolsCenter/ZTools / downloadAsBase64

Method downloadAsBase64

src/main/api/renderer/webSearch.ts:491–564  ·  view source on GitHub ↗

* 下载 URL 内容并转为 base64

(url: string)

Source from the content-addressed store, hash-verified

489 * 下载 URL 内容并转为 base64
490 */
491 private downloadAsBase64(url: string): Promise<string> {
492 return new Promise((resolve) => {
493 const request = net.request(url)
494 const chunks: Buffer[] = []
495 let resolved = false
496 const done = (value: string): void => {
497 clearTimeout(timeout)
498 if (!resolved) {
499 resolved = true
500 resolve(value)
501 }
502 }
503
504 const timeout = setTimeout(() => {
505 if (!resolved) {
506 resolved = true
507 request.abort()
508 resolve('')
509 }
510 }, 10000)
511
512 request.on('response', (response) => {
513 response.on('error', () => {
514 done('')
515 })
516
517 // 处理重定向
518 if (
519 response.statusCode &&
520 response.statusCode >= 300 &&
521 response.statusCode < 400 &&
522 response.headers.location
523 ) {
524 clearTimeout(timeout)
525 resolved = true
526 const location = Array.isArray(response.headers.location)
527 ? response.headers.location[0]
528 : response.headers.location
529 this.downloadAsBase64(location).then(resolve)
530 return
531 }
532
533 if (response.statusCode !== 200) {
534 done('')
535 return
536 }
537
538 const contentType =
539 (Array.isArray(response.headers['content-type'])
540 ? response.headers['content-type'][0]
541 : response.headers['content-type']) || 'image/x-icon'
542
543 response.on('data', (chunk) => {
544 chunks.push(Buffer.from(chunk))
545 })
546 response.on('end', () => {
547 const buffer = Buffer.concat(chunks)
548 if (buffer.length > 0) {

Callers 1

fetchFaviconMethod · 0.95

Calls 1

onMethod · 0.80

Tested by

no test coverage detected