I have the following code, where message is a JSON String. I am trying to upload this to s3 with the md5 of message as the destination filename. I am getting a '505' statusCode. I am new to NodeJS and not sure what I am doing wrong here?
knoxInitParams =
'key': awsKey
'secret': awsPrivateKey
'bucket': bucket
client = knox.createClient knoxInitParams
buff = new Buffer message
reqHeader =
'Content-Length': buff.length
'Content-Type': 'text/plain'
'x-amz-acl': 'private'
req = client.put '/tmp/xxx.txt', reqHeader
req.on 'response', (res) ->
console.log res.statusCode
console.log res.headers
if res.statusCode is 200
console.log res.url
req.on 'error', (err) ->
console.error "S3 Error: ", err
req.end buff
Edit: Changed the destination to hardcode it, as a reply below pointed out that was causing the issue. However, I am now getting a 403 :(
Your code looks fine.
Make sure your date/time are correct. ntpdate -s pool.ntp.org
.
Quick note, I ran into this issue, too, but my error was that I had a space in my filename.
var req = client.put('/tmp/x xx.txt', reqHeader);
I wrapped the filename, like this
var req = client.put(encodeURIComponent('/tmp/x xx.txt'))
Most likely your bug is here:
req = client.put destination.toLowerCase + '.txt', reqHeader
You probably want to invoke destination.toLowerCase
:
req = client.put destination.toLowerCase() + '.txt', reqHeader
On the other hand, I think it's wholly unnecessary -- it will be lowercase already.
On a side note, you may want to look into unit testing -- it's a great way of catching these kinds of bugs! If I were you, I would add a function, say getFileName
:
getFileName = (contents) ->
crypto.createHash('md5').update(contents).digest('hex') + '.txt'
Now you can easily test this function with nodeunit, mocha, jasmine or any of the other great test utilities, and make sure that it always returns what you expect -- and if not, help you notice immediately where the error is.
I can also heartily recommend node's debugger, which also helps you catch these bugs.
When I try your exact code with my own S3 account, it works fine:
$ coffee test
200
{ 'x-amz-id-2': 'f5C32nQHlE0WI8jtNFEZykRFAdrM8ZdBzgeAxc23bnJ2Ti4bYKmcY3pX/KpEzyZg',
'x-amz-request-id': 'B41AACFF85661C2E',
date: 'Tue, 01 May 2012 23:15:39 GMT',
etag: '"44b25eb6d36a88713b7260d8db15b24b"',
'content-length': '0',
server: 'AmazonS3' }
Check your ID/key/bucket, and date/time as @skrewler suggests.