简体   繁体   中英

Streaming Assets (JS/CSS/images) from Amazon S3 with Express.js

I recently deployed my Node.js blog on AppFog. I plan to use a bucket on Amazon S3 to stream my assets (javascript/stylesheets/images).

How can I make sure that Express.js get static assets to my Amazon S3 bucket instead of the regular /public ?

I wouldn't stream assets through the node server – it's a waste of resources, and you're going to have to deal with HTTP caching headers.

Instead, your HTML should link directly to the S3 bucket. Instead of:

<script src="/js/script.js"></script>

Do:

<script src="//s3.amazonaws.com/bucket/js/script.js"></script>

Given that you're migrating, just set up a permanent redirect.

app.get(/^\/(js|css|images)\/.*/, function(req, res) {
    res.redirect(301, '//s3.amazonaws.com/bucket' + req.path);
});

This will redirect all requests for things in the js, css, and images folders to a S3 bucket. For example, /js/script.js would redirect to //s3.amazonaws.com/bucket/js/script.js.

This will help ease the transition, but you should still migrate your site's references to the S3 URLs to eliminate the unnecessary HTTP roundtrip cause by having the redirect.

如果您确实需要这样做,请使用请求库中的pipe(): https//github.com/mikeal/request#streaming

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM