configure sftp in nest.js

584 Views Asked by At

i'm trying to configure sftp server in nest.js using this node package ssh2-sftp-client.but i'm getting a error ssh2_sftp_client_1.SftpClient is not a constructor. this is what i have done so far

this is my service file

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';
  }

this is my controller file

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) {}
  }

anyone here who has configured this package in nest before. any help would be appreciated

1

There are 1 best solutions below

0
Maulik Kakadiya On

Here is my working solution

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

// any random string for identification

connectionId: string;

define the config for sftp connection

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

//declare Client object

private client: Client = new Client(connectionId);

Here is an example of listeners.

     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}`,
        );
      });

// finally connect with client

await this.client.connect(config);