Move folder files via ssh using NodeJS | sftp using NodeJS

Using NodeJS we can create ssh connection to send file or executing any command on Linux based server. Here we are using npm module ssh2 for sftp connection to transfer file from local machine to remote machine. This module does not give any direct option to transfer complete folder in one shot but we can do it file by file.

Here is piece of code which we can use to upload or download file from server.

let fs = require('fs');
let async = require('async');

function uploaddownFiles(connection, fromFolder, toFolder, sftpmethod) {
    return new Promise((resolve, reject) => {
        // Getting all file list in given folder of local machine
        let fileList = fs.readdirSync(fromFolder);
        // filter only files not folders
        fileList = fileList.filter(file => {
            if (file.includes('.')) return true;
            return false;
        console.log('Total files: ', fileList.length)
        if (!fileList.length) return reject('No file to send')
        connection.sftp(function (err, sftp) {
            if (err) return;
            async.eachOfSeries(fileList, (file, key, cb) => {
                let moveFrom = `${fromFolder}/${file}`;
                let moveTo = `${toFolder}/${file}`;
                if (sftpmethod=== 'put')
                    sftp.fastPut(moveFrom, moveTo, {}, function (uploadError) {
                        if (uploadError) return cb(uploadError);
                        console.log("Successfully Uploaded", file);
                else if (sftpmethod === 'get')
                    sftp.fastGet(moveFrom, moveTo, {}, function (uploadError) {
                        if (uploadError) return cb(uploadError);
                        console.log("Successfully Downloaded", file);
            }, function (err) {
                if (err) {
                    return reject(err);
                } else {
                    console.log('all files have been uploaded/downloaded');
                    return resolve();

How to use above function

let ssh = require('ssh2'); // npm i ssh2
let conn = new ssh();
conn.on('ready', async function () {
    // 'put' for uploading file from local to server
    await uploaddownFiles(conn, 'D/xyz', `/home/xyz`, 'put').catch((err) => console.log(err));
    // 'get' for download file from server
    // await uploaddownFiles(conn, `/home/xyz/`, 'D/xyz', 'get').catch((err) => console.log(err));

}).on('error', (err) => console.log(err)).on('connect', () => console.log('Connection :: connected')).connect({
    host: '',
    port: 22,
    username: 'username',
    password: 'password'
    //if want to use ssh key
    // privateKey: fs.readFileSync('Key path')

Reference : npm ssh2

Leave a Reply