Transfer entire directory using ssh2 in Nodejs

末鹿安然 提交于 2019-12-04 15:07:55

A couple of solutions:

  1. You could recursively traverse the directory (making directories and transferring files as needed) using the sftp methods

  2. Tar the directory (compress it too if you want) to stdout (e.g. tar cf - mydir) and then process that incoming stdout data with the tar module (and the built-in zlib module first if you end up compressing the directory).

    // Requires:
    //   * `npm install tar-fs`
    //   * `ssh2` v0.5.x or newer
    var tar = require('tar-fs');
    var zlib = require('zlib');
    
    function transferDir(conn, remotePath, localPath, compression, cb) {
      var cmd = 'tar cf - "' + remotePath + '" 2>/dev/null';
    
      if (typeof compression === 'function')
        cb = compression;
      else if (compression === true)
        compression = 6;
    
      if (typeof compression === 'number'
          && compression >= 1
          && compression <= 9)
        cmd += ' | gzip -' + compression + 'c 2>/dev/null';
      else
        compression = undefined;
    
      conn.exec(cmd, function(err, stream) {
        if (err)
          return cb(err);
    
        var exitErr;
    
        var tarStream = tar.extract(localPath);
        tarStream.on('finish', function() {
          cb(exitErr);
        });
    
        stream.on('exit', function(code, signal) {
          if (typeof code === 'number' && code !== 0) {
            exitErr = new Error('Remote process exited with code '
                                + code);
          } else if (signal) {
            exitErr = new Error('Remote process killed with signal '
                                + signal);
          }
        }).stderr.resume();
    
        if (compression)
          stream = stream.pipe(zlib.createGunzip());
    
        stream.pipe(tarStream);
      });
    }
    
    // USAGE ===============================================================
    var ssh = require('ssh2');
    
    var conn = new ssh();
    conn.on('ready', function() {
      transferDir(conn,
                  '/home/foo',
                  __dirname + '/download',
                  true, // uses compression with default level of 6
                  function(err) {
        if (err) throw err;
        console.log('Done transferring');
        conn.end();
      });
    }).connect({
      host: '192.168.100.10',
      port: 22,
      username: 'foo',
      password: 'bar'
    });
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!