如何使用Node.js从SFTP服务器下载文件?已尝试sftp.fastGet
可以用Node.js实现SFTP文件下载到本地
当然可以,你用到的sftp.fastGet正是ssh2库中高效的文件下载方法,下面是完整的实现方案:
步骤1:安装依赖
先安装ssh2库(这是实现SFTP操作的常用Node.js库):
npm install ssh2
步骤2:完整下载代码示例
const { Client } = require('ssh2'); const fs = require('fs'); const path = require('path'); // SFTP服务器配置 const sftpConfig = { host: '你的SFTP服务器地址', port: 22, // 默认SFTP端口为22 username: '你的SFTP账号', password: '你的SFTP密码', // 也支持私钥认证:privateKey: fs.readFileSync('/本地私钥路径/id_rsa') }; // 确保本地目标文件夹存在 const localSaveDir = './local_downloads'; if (!fs.existsSync(localSaveDir)) { fs.mkdirSync(localSaveDir, { recursive: true }); } // 建立连接并执行下载 const conn = new Client(); conn.on('ready', () => { console.log('已成功连接SFTP服务器'); conn.sftp((err, sftp) => { if (err) throw err; // 远程文件路径(SFTP服务器上的绝对路径) const remoteFilePath = '/remote/path/target_file.pdf'; // 本地保存路径 const localFilePath = path.join(localSaveDir, 'target_file.pdf'); // 使用fastGet下载文件 sftp.fastGet(remoteFilePath, localFilePath, { // 可选:添加下载进度监听 step: (transferredBytes, totalBytes) => { console.log(`下载进度: ${((transferredBytes / totalBytes) * 100).toFixed(2)}%`); } }, (err) => { if (err) { console.error('下载失败:', err.message); } else { console.log('文件已成功下载到本地'); } // 关闭SFTP连接和SSH连接 sftp.end(); conn.end(); }); }); }).on('error', (err) => { console.error('连接SFTP服务器失败:', err.message); }).connect(sftpConfig);
常见问题排查
- 路径错误:确认远程路径是SFTP服务器的绝对路径,本地路径的父文件夹需提前创建(代码中已包含自动创建逻辑)
- 权限问题:检查SFTP账号是否有读取目标文件的权限,本地文件夹是否有写入权限
- 大文件处理:
fastGet默认支持断点续传,无需额外处理大文件场景 - 连接超时:可在
ssh2配置中添加readyTimeout参数设置超时时间,比如readyTimeout: 10000(10秒)
内容的提问来源于stack exchange,提问作者Yethin S
相关产品推荐
相关产品推荐

