Home > Net >  Unable to read css file uploaded to S3 bucket with Node.js
Unable to read css file uploaded to S3 bucket with Node.js

Time:01-11

I have a Node.js app that is meant to upload a css file to S3 to be used by my website. Everything seems to work fine but when I access the file on my website none of the css changes are being applied. I can even see the css file under 'dev tools/sources'. The css in that file though is not taking effect. If I make any change to the file in dev tools the css starts to immediately all work. If I download the file from s3 and then reupload it manually without changing anything that also works. So something to do with the formatting of me adding the file with Node.js is throwing it off. Any help with this would be greatly appreciated.

 let globalStyles = `.header-background{background-color:${themeStyles['headerBackground']};}

//using this to remove backticks from globalStyles
        globalStyles = globalStyles.replace(/^`|`$/g, '');

        await addFileCssS3(css, `${newUrl}/global.css`, newUrl);

const addFileCssS3 = async (file, key, newUrl) => {

    await s3
        .putObject({
            Body: file,
            Bucket: BucketName,
            Key: key,
            ContentType: 'text/css',
        })
        .promise()
        .catch((error) => {
            console.error(error)
        })
}

CodePudding user response:

To fix this, you can try removing the newline from the globalStyles string before passing it to the addFileCssS3 method. There are several ways to do this, one is to simply use the .trim() property to remove any leading and trailing whitespace from a string, ex:

globalStyles = globalStyles.trim(); or by using a regular expression to remove the newline character from the end of the globalStyles string

globalStyles = globalStyles.replace(/\r?\n|\r/g, ''); The second method, using regular expression should work to remove newlines from both Windows and Linux.

Another possible cause could be the failed call to a function that re-inserts the css into the html page, the eventual lack of this function causes the downloaded css not to be used.

If this doesn't solve the problem, I recommend checking the Content-Type header of the css file when uploaded to S3 to make sure it's set correctly. Also check if the S3 bucket permissions or browser caching parameters are configured to not allow the use of the updated css.

  • Related