timshadel
3/13/2013 - 12:06 AM

fixheaders.js

/**
 * Module dependencies
 */
var knox = require('knox')
  , async = require('async')
  , url = require('url');

/**
 *  node fixheaders.js s3://bucket/prefix
 */
var s3 = url.parse(process.argv.slice(2).shift());

var client = knox.createClient({
    key: process.env.S3_ACCESS_KEY
  , secret: process.env.S3_SECRET_KEY
  , bucket: s3.hostname
});

var items = {}
  , count = 0;

function done() {
  console.log('finished', items);
}

client.list({ prefix: s3.pathname.match(/^\/(.*)/)[1] }, function(err, data){
  console.log('list', data.Contents.length, 'items');

  async.eachLimit(data.Contents, 5, function(item, done) {
    console.log('ask', item.Key);
    client.head(item.Key).on('response', function(itemhead) {
      console.log('item', item.Key, itemhead.headers['content-type']);
      client.copy(item.Key, item.Key, {
        'x-amz-acl': 'public-read',
        'x-amz-metadata-directive': 'REPLACE',
        'content-type': itemhead.headers['content-type'],
        'cache-control': 'max-age=60,public'
      }).on('response', function(res){
        console.log('fixed', item.Key, itemhead.headers['content-type']);
        done();
      }).end();
    }).end();
  }, function(err) {
    if (err) { console.error(err); return; }
    console.log('finished');
  });

});