download icon indicating copy to clipboard operation
download copied to clipboard

downloaded file has extension .gi instead of .gif

Open terchris opened this issue 2 years ago • 1 comments

It seems that the last letter is removed when downloading a file that has a long and complex filename.

example file: https://images.squarespace-cdn.com/content/v1/6124a4fd689c806393eb581b/81dc0346-e123-4880-89dd-104e34a4f596/Kanalbyen+-+a+new+destination+in+Kristiansand%2C+Norway-high+%281%29+%28brugt+p%C3%A5+forsiden%29.gif

is saved as: Kanalbyen+-+a+new+destination+in+Kristiansand%2C+Norway-high+%281%29+%28brugt+p%C3%A5+forsiden%29.gi

I'm using a mac

terchris avatar Apr 08 '22 09:04 terchris

this is due to the default maxLength option from the module used to sanitise filename on save: https://github.com/sindresorhus/filenamify#maxlength

if the filename is longer than 100 characters, the module will truncate it. download does not seems to have options to update this default behaviour.

You can use this simple snippet as a replacement:

const fs = require('fs')
const https = require('https')

async function download(url, targetFile) {
    return new Promise((resolve, reject) => {
        https
            .get(url, (response) => {
                const code = response.statusCode ?? 0

                if (code >= 400) {
                    return reject(new Error(response.statusMessage))
                }

                const fileWriter = fs
                    .createWriteStream(targetFile)
                    .on('finish', () => {
                        resolve({})
                    })

                response.pipe(fileWriter)
            })
            .on('error', (error) => {
                reject(error)
            })
    })
}

await download('http://mywebsite.com/path/to/remotefile.gif', `${__dirname}/out/remotefile.gif`)

alwex avatar Jun 14 '23 04:06 alwex