You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Node.js构建SFTP客户端:将服务端lsEntries同步至HTML页面

实现SFTP目录条目从Node.js后端发送到HTML页面

我来帮你搞定把SFTP获取的目录条目传到HTML页面的需求,咱们分后端改造和前端页面开发两部分来实现:


一、后端代码调整

首先先修正你原代码里的小问题,再添加API接口把目录数据返回给前端:

1. 修正基础问题

  • 原代码里app.use(cors)要改成app.use(cors()),否则CORS中间件不会正常生效
  • 补全sftp.readdir的完整逻辑,同时把SFTP操作封装到API路由里,方便前端请求

2. 完整后端代码示例

var Client = require('ssh2').Client;
var express = require('express');
var app = express();
var cors = require('cors');

// 启用CORS中间件
app.use(cors());
// 解析JSON请求体(可选,这里主要用于返回JSON)
app.use(express.json());

// SFTP连接配置(记得替换成你的真实信息)
var connSettings = {
  host: 'myserver',
  port: 22,
  username: 'myuser',
  password: 'passwd'
};
var remotePathToList = '/';

// 创建API接口,返回SFTP目录条目
app.get('/api/sftp-ls', (req, res) => {
  var conn = new Client();
  
  conn.on('ready', function() {
    conn.sftp(function(err, sftp) {
      if (err) {
        console.error('SFTP连接失败:', err);
        return res.status(500).json({ error: 'SFTP连接失败' });
      }
      
      // 读取远程目录
      sftp.readdir(remotePathToList, function(err, lsEntries) {
        if (err) {
          console.error('读取目录失败:', err);
          return res.status(500).json({ error: '读取远程目录失败' });
        }
        
        // 关闭SFTP和SSH连接
        sftp.end();
        conn.end();
        
        // 将目录条目返回给前端
        res.json(lsEntries);
      });
    });
  });
  
  conn.on('error', function(err) {
    console.error('SSH连接失败:', err);
    res.status(500).json({ error: 'SSH连接失败' });
  });
  
  // 发起SSH连接
  conn.connect(connSettings);
});

// 启动服务器,监听3000端口
app.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000');
});

二、前端HTML页面开发

写一个简单的HTML页面,通过fetch请求后端API,然后把返回的目录条目渲染出来:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>SFTP目录查看器</title>
  <style>
    table { border-collapse: collapse; width: 80%; margin: 20px auto; }
    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
    th { background-color: #f2f2f2; }
  </style>
</head>
<body>
  <h1 style="text-align: center;">SFTP远程目录</h1>
  <div id="loading" style="text-align: center;">加载中...</div>
  <table id="fileTable" style="display: none;">
    <thead>
      <tr>
        <th>文件名</th>
        <th>类型</th>
        <th>大小(字节)</th>
        <th>修改时间</th>
      </tr>
    </thead>
    <tbody id="fileBody"></tbody>
  </table>
  <div id="error" style="text-align: center; color: red; display: none;"></div>

  <script>
    // 后端API地址
    const apiUrl = 'http://localhost:3000/api/sftp-ls';

    // 请求并渲染目录数据
    fetch(apiUrl)
      .then(response => {
        if (!response.ok) throw new Error('请求失败');
        return response.json();
      })
      .then(lsEntries => {
        document.getElementById('loading').style.display = 'none';
        const fileBody = document.getElementById('fileBody');
        // 遍历目录条目,生成表格行
        lsEntries.forEach(entry => {
          const row = document.createElement('tr');
          row.innerHTML = `
            <td>${entry.filename}</td>
            <td>${entry.longname.charAt(0) === 'd' ? '目录' : '文件'}</td>
            <td>${entry.attrs.size}</td>
            <td>${new Date(entry.attrs.mtime * 1000).toLocaleString()}</td>
          `;
          fileBody.appendChild(row);
        });
        document.getElementById('fileTable').style.display = 'table';
      })
      .catch(error => {
        document.getElementById('loading').style.display = 'none';
        document.getElementById('error').textContent = `加载失败: ${error.message}`;
        document.getElementById('error').style.display = 'block';
      });
  </script>
</body>
</html>

三、运行步骤

  1. 确保你已经安装了所有依赖:npm install ssh2 express cors
  2. 启动后端Node.js服务
  3. 打开上述HTML页面(直接在浏览器打开即可),就能看到SFTP远程目录的内容了

注意事项

  • 记得把后端代码里的connSettings替换成你的真实SFTP服务器信息
  • 如果后端和前端不在同一域名下,CORS配置已经帮你处理了,但生产环境建议限制允许的域名
  • 每次请求API都会新建一个SFTP连接,生产环境可以考虑连接池优化

内容的提问来源于stack exchange,提问作者Ronny Brandt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:01:29