Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy file from one AWS S3 Bucket to another bucket with Node

I am trying to copy a file from a AWS S3 bucket to another bucket using Node. The problem is if the file name doesn't has the white space for example: "abc.csv", It is working fine. But in case the file to which I want to copy has the white space in the file name for example: "abc xyz.csv". It is throwing the below error.

"The specified key does not exist." "NoSuchKey: The specified key does not exist. at Request.extractError (d:\Projects\Other\testproject\s3filetoarchieve\node_modules\aws-sdk\lib\services\s3.js:577:35)

Below is the code provided.

return Promise.each( files, file => {
        var params = {
            Bucket: process.env.CR_S3_BUCKET_NAME, 
            CopySource: `/${ process.env.CR_S3_BUCKET_NAME }/${ prefix }${ file.name}`, 
            Key: `${ archieveFolder }${ file.name }`
        };
        console.log(params);
        return new Promise(( resolve, reject) => {
            s3bucket.copyObject(params, function(err, data) {
                if (err){
                    console.log(err, err.stack); 
                    debugger
                } else {
                    console.log(data); 
                    debugger
                }             
            });
        });
    }).then( result => {
        debugger
    });

Early help would be highly appreciable. Thank you.

like image 514
Mohit Dixit Avatar asked Oct 27 '25 08:10

Mohit Dixit


1 Answers

I think the problem is exactly that space in the filename.

S3 keys must be url encoded, as they need to be accesible in URL form. There are some packages that helps you with url formatting like speakingUrl or you can try writting some on your own, maybe just simply replacing spaces (\s) with dashes (_ or -) if you want to keep it friendly.

If you don't mind about that, you can simply encodeURIComponent(file.name)

Hope it helps!

like image 88
gtrenco Avatar answered Oct 29 '25 23:10

gtrenco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!