Nest SFTP Module

3.1.0 · active · verified Sun Apr 19

nest-sftp is a NestJS framework module that provides a wrapper around the `ssh2-sftp-client` library, enabling SFTP client capabilities within a NestJS application. It integrates SFTP connection management directly into the NestJS dependency injection system, allowing for easy configuration and use of SFTP operations. The current stable version is 3.1.0, which includes support for NestJS 11. While minor releases and bug fixes occur periodically, major version updates are less frequent, often coinciding with significant changes or new NestJS version support. Key differentiators include its seamless integration with Nest's module system, supporting both synchronous (`forRoot`) and asynchronous (`forRootAsync`) configuration patterns, and the ability to inject a configured `SftpClientService` directly into other services for file transfer operations.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates registering the SftpModule asynchronously, injecting SftpClientService, and performing basic SFTP operations like listing, uploading, downloading, and deleting files.

import { Module, Injectable, Logger } from '@nestjs/common';
import { SftpModule, SftpClientService } from 'nest-sftp';
import { ConnectConfig } from 'ssh2-sftp-client';

@Injectable()
class ConfigService {
  getSftpConnectionInfo(): ConnectConfig {
    // In a real app, fetch these from environment variables or a configuration store
    return {
      host: process.env.SFTP_HOST ?? 'sftp.example.com',
      port: parseInt(process.env.SFTP_PORT ?? '22', 10),
      username: process.env.SFTP_USERNAME ?? 'user',
      password: process.env.SFTP_PASSWORD ?? 'password',
      // Optional: debug logging
      debug: console.log
    };
  }
}

@Injectable()
export class AppService {
  private readonly logger = new Logger(AppService.name);
  constructor(private readonly sftpClient: SftpClientService) {}

  async runSftpExample(): Promise<void> {
    try {
      this.logger.log('Attempting to list SFTP directory...');
      const list = await this.sftpClient.list('/remote/path');
      this.logger.log(`Listed directory: ${JSON.stringify(list.map(f => f.name))}`);

      const remoteFile = `/remote/path/test-${Date.now()}.txt`;
      const localContent = 'Hello SFTP from NestJS!';
      const buffer = Buffer.from(localContent);

      this.logger.log(`Uploading file to ${remoteFile}`);
      await this.sftpClient.upload(buffer, remoteFile);
      this.logger.log('File uploaded successfully.');

      this.logger.log(`Downloading file from ${remoteFile}`);
      const downloadedBuffer = await this.sftpClient.download(remoteFile);
      this.logger.log(`Downloaded content: ${downloadedBuffer.toString()}`);

      this.logger.log(`Deleting file ${remoteFile}`);
      await this.sftpClient.delete(remoteFile);
      this.logger.log('File deleted successfully.');

    } catch (error) {
      this.logger.error('SFTP operation failed:', error.message);
    }
  }
}

@Module({
  imports: [
    SftpModule.forRootAsync(
      {
        useFactory: (configService: ConfigService) => {
          return configService.getSftpConnectionInfo();
        },
        inject: [ConfigService],
        imports: [ConfigService],
      }
    ),
  ],
  controllers: [],
  providers: [ConfigService, AppService],
  exports: [ConfigService, AppService]
})
export class AppModule {
  constructor(private readonly appService: AppService) {
    // Kick off the SFTP example when the app starts
    // This would typically be triggered by an endpoint or lifecycle hook in a real app
    this.appService.runSftpExample();
  }
}

view raw JSON →