使用Bluebird实现节点SSH2 SFTP

时间:2017-05-19 06:36:41

标签: node.js bluebird

我正在使用https://github.com/mscdex/ssh2来满足我的FTP要求。 我尝试了下面提到的代码:

'use strict';

global.Promise = require("bluebird");
global._ = require('lodash');

var Client = Promise.promisifyAll(require('ssh2').Client);
Promise.promisifyAll(Client.prototype);

var clientObject, conn;

function getClient() {
    return new Promise((resolve, reject) => {
        if (clientObject) resolve(clientObject);

        let authObj = {
            host: 'abc',
            port: 22,
            username: 'name',
            password: 'password'
        };

        conn = new Client();
        conn.connect(authObj);

        conn.on('ready', () => {
            conn.sftp((err, sftp) => {
                if (err) reject(err);
                clientObject = sftp;
                resolve(clientObject)
            });
        });

        conn.on('error', (err) => { reject(err) });
    });
}


function getList(){
    getClient().then((cObj)=>{
        cObj.readdir('.').then((list)=>{
            _.each(list, (file)=>{console.log(file.filename)});
        });
    });
}


getList();

上面给出错误:

Unhandled rejection TypeError: cObj.readdir(...).then is not a function
.
.
.
/home/nk/test/node_modules/ssh2-streams/lib/sftp.js:1583
            cb(undefined, entries);
            ^

TypeError: cb is not a function
    at /home/nk/test/node_modules/ssh2-streams/lib/sftp.js:1583:13

从上面的错误;看起来它指向这一行https://github.com/mscdex/ssh2-streams/blob/master/lib/sftp.js#L1583

有可能实现吗?

1 个答案:

答案 0 :(得分:0)

我已经创建了一个ssh2-promise npm包,用于提供相同的服务。我已经宣传了SSH2和SFTP项目。希望它会有所帮助