Gulp.js + Azure Blob Storage

September 23, 2014

Blog | Development | Gulp.js + Azure Blob Storage
Gulp.js + Azure Blob Storage

Gulp is a Node.js task-runner that allows you to simplify repetitive tasks like minification, compilation, unit testing, linting, etc. With a rich knowledge base, and hundreds of plugins and resources, you can use gulp to automate nearly anything with minimum of effort. I love using it as a build system for projects, so I turned to it to create a method of uploading static web content to a Microsoft Azure Blob Storage account without writing a custom tool.

To accomplish this, I used the NPM packages deploy-azure-cdn to manage uploading to the storage account in conjunction with gulp-ignore to filter unnecessary files.

Once you have nodejs and npm installed on your machine, create a package.json file. This configures the npm dependencies our Gulp build script will rely on.

{
    "name": "build",
    "version": "1.0.0",
    "description": "Build script",
    "author": "Justin Firth",
    "repository": {
        "type": "hg",
        "url": "https://bitbucket.org/jmfirth/gulpazure"
    },
    "dependencies": {
        "gulp": "^3.8.7",
        "deploy-azure-cdn": "^0.1.2",
        "gulp-ignore": "^1.2.0"
    },
    "devDependencies": {}
}

Afterward, run npm install to download and install these dependencies in your local source folder.

npm install

Next, create a gulpfile.js build script. This script contains a single task, publishAzure, that takes a set of source files, pipes them through an exclusion filter, and then uploads them to the destination container.

// dependencies
var gulp = require('gulp')
,   deployCdn = require('deploy-azure-cdn')
,   gulpIgnore = require('gulp-ignore')
,   path = require('path');

var accountName = ''; // Azure Blob Storage account name
var accountKey = ''; // Azure Blob Storage account key

// gulp task for publishing to Azure Blob Storage
gulp.task('publishAzure', function() {
    var cwd = path.resolve(path.dirname('gulpfile.js'), 'src');
    return gulp
        // include source files
        .src(['**'], { cwd: cwd })
        // pipe through exclusion filter
        .pipe(gulpIgnore.exclude(['**\*.md']))
        // upload to blob storage
        .pipe(deployCdn.gulpPlugin({
                containerName: 'content',
                serviceOptions: [accountName, accountKey],
                folder:  '',
                zip: true,
            }));
});

// make 'publishAzure' task the default
gulp.task('default', [ 'publishAzure' ]);

Finally, run gulp publishAzure to execute this task, uploading filtered content to the destination container of your storage account.

gulp publishAzure

The source for this example is available in a public repository.

Justin Firth

UX/Front End Practice Lead
Tags
  • Node.js
  • Tutorial

Recent Work

Check out what else we've been working on