在nest.js中配置sftp

问题描述 投票:0回答:1

我正在尝试使用此节点包 ssh2-sftp-client 在 Nest.js 中配置 sftp 服务器。但是我收到错误 ssh2_sftp_client_1.SftpClient 不是构造函数。 这就是我到目前为止所做的

这是我的服务文件

import { Inject, Injectable } from '@nestjs/common';
import { SftpClient, ConnectConfig, FileInfo } from 'ssh2-sftp-client';

export class ServerService {
  private sftp: SftpClient;
  constructor() {
    this.sftp = new SftpClient();
  }

  async connect(config: ConnectConfig): Promise<any> {
    await this.sftp.connect(config);
    return 'server connected';
  }

这是我的控制器文件

import { Controller, Inject } from '@nestjs/common';
import { ServerService } from './server.service';

@Controller('server')
export class ServerController {
  constructor(
    @Inject(ServerService) private readonly sftpService: ServerService,
  ) {}

  async connect() {
    try {
      await this.sftpService.connect({
        host: 'something',
        port: portnumber,
        username: 'username',
        password: 'password',
      });
    } catch (e) {}
  }

这里的任何人之前都在nest中配置过这个包。任何帮助将不胜感激

node.js nestjs node-modules ssh2-sftp
1个回答
0
投票

这是我的工作解决方案

//import CLient from 'ssh2-sftp-client
import Client = require('ssh2-sftp-client');

//任意随机字符串用于识别

connectionId: string;

定义 sftp 连接的配置

const config = {
  host: 'example.com',
  port: 22,
  username: 'red-don',
  password: 'my-secret'
};

//声明Client对象

private client: Client = new Client(connectionId);

这是监听器的示例。

     await this.client.on('close', function () {
        logger.info(
          `connection closed and onClose Listeners called for connectionId ${this.connectionId}`,
        );
        /** your impl for handle Listeners */
      });

      await this.client.on('end', function () {
        logger.info(
          `connection closed and onEnd Listeners called for connectionId ${this.connectionId}`,
        );
        /** your impl for handle Listeners */
      });

      await this.client.on('error', function () {
        logger.info(
          `connection closed and onError Listeners called for connectionId ${this.connectionId}`,
        );
         /** your impl for handle Listeners */
      });

      await this.client.on('ready', function () {
        logger.info(
          `connection established and onReady Listeners called for connectionId ${this.connectionId}`,
        );
      });

//终于与客户端连接了

await this.client.connect(config);
      
© www.soinside.com 2019 - 2024. All rights reserved.