SFTP module in netsuite

The N/sftp module in NetSuite SuiteScript 2.x allows developers to connect to remote servers using the Secure File Transfer Protocol (SFTP). This module is useful for transferring files securely between a NetSuite account and an external server. You can use it to upload or download files, list directories, and manage files on a remote server.

1. Establishing an SFTP Connection

To establish an SFTP connection, you first need to create an SFTP connection object using the N/sftp.createConnection(options) method. This method requires parameters such as the URL of the remote server, port number, credentials, and key authentication if necessary.

define([‘N/sftp’, ‘N/encode’], function(sftp, encode) {

  function getConnection() {

    var connection = sftp.createConnection({

      url: ‘sftp.example.com’,     // SFTP host URL

      port: 22,             // SFTP port, default is 22

      username: ‘your-username’,    // SFTP username

      passwordGuid: ‘12345’,      // Scripted Record ID of the Password Credentials

      privateKeyGuid: ‘abcdefg’,    // Scripted Record ID of the Private Key

      passphrase: encode.convert({

        string: ‘your-passphrase’,  // Passphrase to decrypt the private key

        inputEncoding: encode.Encoding.UTF_8,

        outputEncoding: encode.Encoding.BASE_64

      })

    });

    return connection;

  }

});

2. Uploading a File

After establishing a connection, you can upload a file using the upload() method of the connection object.

var connection = getConnection();

connection.upload({

  directory: ‘/upload_directory/’,   // Remote directory path

  filename: ‘example.txt’,       // Name of the file on the remote server

  file: fileObj,            // NetSuite file object to upload

  replaceExisting: true         // Whether to overwrite an existing file with the same name

});

3. Downloading a File

To download a file from the remote SFTP server, use the download() method.

var fileContent = connection.download({

  directory: ‘/download_directory/’,  // Remote directory path

  filename: ‘example.txt’        // Name of the file to download

});

Key Methods in the N/sftp Module:

  • createConnection(options): Establishes an SFTP connection.
  • upload(options): Uploads a file to the remote server.
  • download(options): Downloads a file from the remote server.
  • list(options): Lists the contents of a remote directory.
  • remove(options): Deletes a file on the remote server.
  • move(options): Renames or moves a file on the remote server.

Leave a comment

Your email address will not be published. Required fields are marked *