Skip to content

Instantly share code, notes, and snippets.

@joniahola
Last active April 7, 2019 15:26
Show Gist options
  • Save joniahola/322b3dd22520c962ac3204d5f73a0224 to your computer and use it in GitHub Desktop.
Save joniahola/322b3dd22520c962ac3204d5f73a0224 to your computer and use it in GitHub Desktop.
Sync between local and remote files using gulp. Developing your local machine and upload all changes to remote server. Just run `npm install`, fill property fields to `.settings.json` and run `gulp watch`. Tested node v8.7.0
const gulp = require('gulp'); //Example version ~3.9.1
const watch = require('gulp-watch'); //Used plugin because it's better. Example version ^5.0.1
const sftp = require('gulp-sftp'); //Example version ^0.1.5
const GulpSSH = require('gulp-ssh'); //Example version ^0.7.0
const fs = require('fs');
const settings = require('./.settings.json'); //credentials hide there
const sftpConfig = {
host: settings.host,
user: settings.user,
remotePath: settings.remotePath,
key: {
location: settings.privatekey
}
}
const sshConfig = {
host: settings.host,
username: settings.user,
privateKey: fs.readFileSync(settings.privatekey)
}
const ssh = new GulpSSH({
ignoreErrors: false,
sshConfig: sshConfig
});
const targets = settings.targets; //settings property is array type
gulp.task("watch", function() {
watch(targets, {}, function(obj) {
if(['change', 'add'].indexOf(obj.event) !== -1) {
const event = obj.event === 'change' ? 'updating' : 'creating';
const path = obj.dirname.replace(__dirname + '/', '') + '/';
const modifiedSftpConfig = Object.assign({}, sftpConfig);
modifiedSftpConfig.remotePath += path;
console.log('---File ' + event + '---');
gulp.src(obj.path)
.pipe(sftp(modifiedSftpConfig));
}
else if(obj.event === 'unlink') {
const file = obj.basename;
let path = obj.dirname.replace(__dirname + '/', '') + '/';
path = settings.remotePath + path + file;
console.log('---File removing---');
ssh.exec('rm ' + path);
}
});
});
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"gulp": "~3.9.1",
"gulp-sftp": "^0.1.5",
"gulp-ssh": "^0.7.0",
"gulp-watch": "^5.0.1"
}
}
{
"host": "123.45.67.89",
"user": "user",
"privatekey": "/a/b/c/d",
"remotePath": "/p/p2/p3/",
"targets": [
"/loc1/loc2/loc3/"
]
}
@joniahola
Copy link
Author

joniahola commented Apr 6, 2019

Btw, gulp-sshdoesn't like ~mark. So use absolute path without any fancy shortcut marks. Example ~/.ssh/ is not maybe work but if you write /User/user/.ssh/ that work.

@joniahola
Copy link
Author

EDIT: updated gulpfile.js because of directories problem in remote server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment