Skip to content

Instantly share code, notes, and snippets.

@lucamug
Created November 15, 2016 16:12
Show Gist options
  • Save lucamug/203931a35143ad7ef09c239ade4411bc to your computer and use it in GitHub Desktop.
Save lucamug/203931a35143ad7ef09c239ade4411bc to your computer and use it in GitHub Desktop.
Minimal Javascript code to upload a file using sftp. It requires ssh2
var fs = require('fs'),
client = require('ssh2').Client;
upoladFile({
localFolder: "",
localFile: "",
remoteFolder: "",
remoteFile: "",
host: "",
port: 0,
username: "",
password: ""
});
function upoladFile(p) {
var conn = new client();
conn.on('ready', function () {
conn.sftp(function (err, sftp) {
if (err) throw err;
sftp.readdir(p.remoteFolder, function (err, list) {
if (err) throw err;
console.dir(list);
var readStream = fs.createReadStream(p.localFolder + p.localFile);
var writeStream = sftp.createWriteStream(p.remoteFolder + p.remoteFile, { mode: 0100664 });
writeStream.on('close', function () {
sftp.readdir(p.remoteFolder, function (err, list) {
if (err) throw err;
console.dir(list);
conn.end();
});
});
readStream.pipe(writeStream);
});
});
}).connect({ host: p.host, port: p.port, username: p.username, password: p.password });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment