In this blog I will be showing how you could write a gulp.js script to automate the process of uploading files to a server through FTP. Gulp.js is a javascript task runner, which could be used to automate several tasks like building and deploying during development.

Installation

Installing gulp is just as easy as 3 simple steps.

  • Install gulp globally (using npm)
npm install -g gulp

or

npm install --global gulp
  • Install gulp in devDependencies (package.json should be available within the project directory)
npm install --save-dev gulp
  • Create the gulpfile.js file (this will contain all the code for your tasks)

Now what I intend to do here is to write a task which would automatically deploy all the necessary files of a website project I am working on to a remote server through FTP. I will be using the vinyl-ftp package to create and manage the FTP connection with the remote server.

To start with, lets import the required packages into our gulpfile:

const gulp = require('gulp');
const gutil = require('gulp-util');
const ftp = require('vinyl-ftp');

Then lets tell what files the gulp task should upload into the remote server:

var localFiles = ['./assets/**/*', '*.ico', '*.js', '*.html'];

Here /**/* denotes all the files including the ones in all sub-directories.

Next, lets create the function to create the FTP connection:

var user = process.env.FTP_USER;
var password = process.env.FTP_PASSWORD;

function getFtpConnection() {
  return ftp.create({
    host: 'enter_your_host_here',
    port: 21,
    user: user,
    password: password,
    log: gutil.log
  });
}

Now its time to write the task:

const remoteLocation = 'location_on_your_remote_server';

gulp.task('remote-deploy', function() {
  var conn = getFtpConnection();
  return gulp.src(localFiles, { base: '.', buffer: false })
    .pipe(conn.newer(remoteLocation))
    .pipe(conn.dest(remoteLocation));
});

The way we could run this task is:

FTP_USER=<user> FTP_PASSWORD=<password> gulp remote-deploy