Saturday, July 23, 2016

Small Node/Javascript code to upload a file using sftp

This script upload a file using sftp. Before running it be sure to
  • Install NodeJS
  • Install ssh2 (npm install ssh2)
  • Fill the parameters at the top of the file
The script also list all the file in the folder before and after the uploading




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 });
}
view raw sftp-upload.js hosted with ❤ by GitHub

No comments :

Post a Comment