当前位置: 代码迷 >> 综合 >> NodeJS sftp 上传文件
  详细解决方案

NodeJS sftp 上传文件

热度:23   发布时间:2024-02-21 09:07:56.0

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()).then(() => {
    console.log(`upload ${
      remotePath} success`);resolve();}).catch(err => 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()).then(() => {
    console.log(`upload ${
      remotePath} success`);resolve();}).catch(err => reject(err))});}
}
module.exports = SftpTool;// SftpTool test
const SftpTool = require('./sftp');
const config = {
    host: 'your ip',port: '22', // default 22username: '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. 其他, windows 上安装 sftp 服务

参考