MCPcopy Create free account
hub / github.com/JasonShin/sqlx-ts / downloadFile

Function downloadFile

node/postinstall.js:69–103  ·  view source on GitHub ↗
(url, destination, redirectCount = 0)

Source from the content-addressed store, hash-verified

67
68// Download file from URL
69function downloadFile(url, destination, redirectCount = 0) {
70 return new Promise((resolve, reject) => {
71 if (redirectCount > 5) {
72 return reject(new Error("Too many redirects while downloading file"))
73 }
74
75 const file = fs.createWriteStream(destination)
76 https.get(url, (response) => {
77 if (response.statusCode === 302 || response.statusCode === 301) {
78 // Handle redirects
79 // Close the current file and delete it
80 // Then download from the new location
81 file.close()
82 safeUnlink(destination)
83 return downloadFile(response.headers.location, destination, redirectCount + 1)
84 .then(resolve)
85 .catch(reject)
86 }
87
88 if (response.statusCode !== 200) {
89 file.close()
90 safeUnlink(destination)
91 return reject(new Error(`Failed to download: ${response.statusCode} ${response.statusMessage}`))
92 }
93
94 response.pipe(file)
95 file.on('finish', () => {
96 file.close(resolve)
97 })
98 }).on('error', (err) => {
99 safeUnlink(destination)
100 reject(err)
101 })
102 })
103}
104
105// Calculate SHA-256 hash of a file
106function calculateSHA256(filePath) {

Callers 1

installFunction · 0.85

Calls 2

safeUnlinkFunction · 0.85
pipeMethod · 0.80

Tested by

no test coverage detected