Automate a FTP upload with Gulp.js

Nandun Bandara
SLIIT FOSS Community
2 min readAug 11, 2017

Gulp is a toolkit to help you out of the nightmare of recurring tasks during your development workflow and help you save time to do more awesome stuff with code. Anyways here I will be showing you how I got myself comfortable with deploying a website I developed as a side project, to the remote server.

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
  • This should be done in every single project you plan to use gulp in.
  • package.json should be available within the project directory. You could create it manually or use npm init to generate it automatically.
npm install --save-dev gulp
  • Create the gulpfile.js file
  • This will contain all the code that you would make use of to automate 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. This could be a real headache to do every once in awhile when a change is made in an evolving project like what I am dealing with now. Let’s get on with the code.

I will be using the vinyl-ftp package to create and manage the FTP connection with the remote server. Read the full documentation here.

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

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

Then lets tell what files the gulp task should upload into the remote server. For that we’ll use wildcards to specify.

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 and the required variables.

var user = process.env.FTP_USER;
var password = process.env.FTP_PASSWORD;
function getFtpConnection(){
return ftp.create({
host: <enter your host address here>,
port: 21,
user: user,
password: password,
log: gutil.log
});
}

Here we set the gutil.log to run the task in verbose mode, which means that you get to see which step is being executed and what its status is.

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_PWD=<password> gulp remote-deploy

--

--