Last Updated: February 25, 2016
·
14.55K
· Ionut-Cristian Florescu

Using Amazon S3 in a Node.js application

If you're using Node.js to build "generic" web projects (like this one), chances are that you are going to need to process and store user-uploaded images at some point.

Using Amazon S3 in Node.js

While ImageMagick works perfectly on most PaaS providers, usually the "local" filesystem space is volatile, so you have to come up with your own space/strategy to store images or other type of user-generated assets. There are, of course, fully-featured image management solutions in the cloud - Cloudinary being perhaps the best known at the moment.

But if you're after a really cheap (yet very reliable) alternative, you should take a look at the classic Amazon S3. There are quite a few Node.js modules out there and I've tried some of them, but in the end I ended up working with aws-sdk, the "official" one.

Although I was initially a bit put off by their verbose documentation style, in the end I found it to be quite easy to use.

You can configure it like this (IcedCoffeeScript code):

aws = require 'aws-sdk'
env = process.env

aws.config.update
  accessKeyId:     env.S3_KEY
  secretAccessKey: env.S3_SECRET
  region:          env.S3_REGION

s3 = new aws.S3

And here's a sample method to upload a local (temporary) file:

exports.upload = (tempFilePath, callback) ->
  fileName = path.basename tempFilePath
  await fs.readFile tempFilePath, defer err, data
  return callback err if err
  await
    s3.putObject
        Bucket:       env.S3_BUCKET
        Key:          "pictures/#{fileName}"
        ContentType:  'image/jpg'
        CacheControl: 'max-age=31536000' # 1 year
        Body:         data
      , defer err
    return callback err if err
  await fs.unlink tempFilePath, defer err
  callback err

Not exactly rocket-science, is it?...