NodeJS sftp 上传文件

1. 使用 ssh2-sftp-client 上传文件到 sftp

npm i ssh2-sftp-client -s

2. 核心代码:

// SftpTool 
const Client = require('ssh2-sftp-client');
/**
 * sftp tool
 */
class SftpTool {

  /**
   * {host: ip, port: 22, username: name, password: pwd}
   * @param {Object} config
   */
  constructor(config) {
    this.config = config;
  }

  /**
   * upload data
   * @param {object} data filePath | buffer | readable stream
   * @param {sring} remotePath 
   */
  uploadData(data, remotePath) {
    return new Promise((resolve, reject) => {
      const sftp = new Client();
      sftp.connect(this.config)
        .then(() => sftp.put(data, remotePath))
        .then(() => {
          sftp.end();
          console.log(`upload ${remotePath} success`);
          resolve();
        }).catch(err => {
          sftp.end();
          console.log(`upload ${remotePath} fail`);
          reject(err);
        })
    });
  }

  /**
   * upload local file
   * @param {string} filePath local file path
   * @param {string} remotePath 
   */
  uploadFile(filePath, remotePath) {
    return new Promise((resolve, reject) => {
      const sftp = new Client();
      sftp.connect(this.config)
        .then(() => sftp.fastPut(filePath, remotePath))
        .then(() => {
          sftp.end();
          console.log(`upload ${remotePath} success`);
          resolve();
        }).catch(err => {
          sftp.end();
          console.log(`upload ${remotePath} fail`);
          reject(err);
        })
    });
  }
}
module.exports = SftpTool;

// SftpTool test
const SftpTool = require('./sftp');
const config = {
  host: 'your ip',
  port: '22', // default 22
  username: 'sftp name',
  password: 'sftp password'
};
const sftp = new SftpTool(config);
sftp.uploadData(Buffer.from('test sftp upload'), '/buffer-test.txt');
sftp.uploadFile('./upload-file.txt', '/upload-file.txt');

3. 同步写法

// async test
const Client = require('ssh2-sftp-client');
const sftpTest = new Client();
const config = {
  host: 'your ip',
  port: '22',
  username: 'test',
  password: 'test'
};
async function test() {
  try {
    await sftpTest.connect(config);
    await sftpTest.put(Buffer.from('async test'), '/async.txt');
    await sftpTest.end();
    console.log('upload success');
  } catch (err) {
    sftpTest.end();
    console.error(err);
  }
}
test();

4. 其他, windows 上安装 sftp 服务

参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值