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();