N/sftp Module Script Samples

The following script samples demonstrate how to use the features of the N/sftp module:

Upload and Dowload a File

The following sample shows how to upload and download a file.

To obtain a real host key, use ssh-keyscan <domain>.

To create a real password GUID, obtain a password value from a credential field on a form. For more information, see Form.addCredentialField(options). Also see N/https Module Script Samples for a Suitelet sample that shows creating a form field that generates a GUID.

Note:

This sample script uses the require function so that you can copy it into the SuiteScript Debugger and test it. You must use the define function in an entry point script (the script you attach to a script record and deploy). For more information, see SuiteScript 2.x Script Basics and SuiteScript 2.x Script Types.

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

            /**
 * @NApiVersion 2.1
 */
require(['N/sftp', 'N/file'], (sftp, file) => {
    const myPwdGuid = "B34672495064525E5D65032D63B52301";
    const myHostKey = "AAA1234567890Q=";

    // Establish a connection to a remote FTP server
    let connection = sftp.createConnection({
        username: 'myuser',
        passwordGuid: myPwdGuid,
        url: 'host.somewhere.com',
        directory: 'myuser/wheres/my/file',
        hostKey: myHostKey
    });

    // Create a file to upload using the N/file module
    let myFileToUpload = file.create({
        name: 'originalname.js',
        fileType: file.Type.PLAINTEXT,
        contents: 'I am a test file.'
    });

    // Upload the file to the remote server
    connection.upload({
        directory: 'relative/path/to/remote/dir',
        filename: 'newFileNameOnServer.js',
        file: myFileToUpload,
        replaceExisting: true
    });

    // Download the file from the remote server
    let downloadedFile = connection.download({
        directory: 'relative/path/to/file',
        filename: 'downloadMe.js'
    });
}); 

          

Manage Files and Directories

The following sample shows how you can manage files and directories.

Note:

This sample script uses the require function so that you can copy it into the SuiteScript Debugger and test it. You must use the define function in an entry point script (the script you attach to a script record and deploy). For more information, see SuiteScript 2.x Script Basics and SuiteScript 2.x Script Types.

Important:

This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.

            /**
 * @NApiVersion 2.1
 */
require(['N/sftp', 'N/file'], (sftp, file) => {
    // Establish a connection
    log.debug('Establishing SFTP connection...');
    let connection = sftp.createConnection({
        username: 'sftpuser',
        keyId: 'custkeysftp_nft_demo_key',
        url: 'myurl',
        port: 22,
        directory: 'inbound',
        hostKey: 'myhostkey'
    });
    log.debug('Connection established!');
     
    // List the directory and log the number of elements there
    let list = connection.list({
        path: 'yyy/test'
    });
    log.debug('Items in directory "test" at the beginning: ' + list.length);
 
    // Generate the test file
    log.debug('Generating test file...');
    let myFileToUpload = file.create({
        name: 'asdf.txt',
        fileType: file.Type.PLAINTEXT,
        contents: 'I am a test file.'
    });
    log.debug('Test file generated, uploading to "test" directory...');
 
    // Upload the test file
    connection.upload({
        directory: 'yyy/test',
        filename: 'af.txt',
        file: myFileToUpload,
        replaceExisting: true
    });
    log.debug('Upload complete!');
 
    // List the directory to confirm there is one more file than before
    list = connection.list({
        path: 'yyy/test'
    });
    log.debug('Items in directory "test" after the upload: ' + list.length);
 
    // Create a new directory
    log.debug('Creating directory "test2"...');
    try {
        connection.makeDirectory({
            path: 'yyy/test2'
        });
        log.debug('Directory created.');
    } catch (e) {
        log.debug('Directory not created.');
        log.error(e.message);
    }
    list = connection.list({
        path: 'yyy/test2'
    });
    log.debug('Items in directory "test2": ' + list.length);
 
    // Move the test file to the new directory
    log.debug('Moving the test file from "test" to "test2"...');
    connection.move({
        from: 'yyy/test/af.txt',
        to: 'yyy/test2/af.txt'
    })
    log.debug('File moved!');
 
    // List the original directory again to see the file is moved
    list = connection.list({
        path: 'yyy/test'
    });
    log.debug('Items in directory "test" after the upload: ' + list.length);
 
    // List the new directory for the file
    list = connection.list({path: 'yyy/test2'});
    log.debug('Items in directory "test2" after the upload: ' + list.length);
    log.debug(JSON.stringify(list));
 
    // Try to remove the directory
    log.debug('Removing directory "test2"...');
    try {
        connection.removeDirectory({
            path: 'yyy/test2'
        });
        log.debug('Directory removed!');
    } catch (e) {
        log.debug('Directory not removed!');
        log.error(e.message);
    }
 
    // The directory is not empty so delete the file first
    log.debug('Removing test file from "test2" directory...');
    connection.removeFile({
        path: 'yyy/test2/af.txt'
    });
    log.debug('Test file removed!');
     
    list = connection.list({
        path: 'yyy/test2'
    });
    log.debug('Items in directory "test2": ' + list.length);
 
    // Try to remove the directory again
    log.debug('Removing directory "test2"...');
    try {
        connection.removeDirectory({
            path: 'yyy/test2'
        });
        log.debug('Directory removed!');
    } catch (e) {
        log.debug('Directory not removed!');
        log.error(e.message);
    }
 
    // Try to list the removed directory
    log.debug('Trying to list directory "test2"...');
    try {
        list = connection.list({
            path: 'yyy/test2'
        });
    } catch (e) {
        log.error(e.message);  
    }
}); 

          

Set Conditional Default Settings Using N/sftp Enums

The following sample shows how to use the N/sftp module enums to set conditional default settings. The sample creates a secure connection and attempts to upload and add a large file.

Note:

This script sample uses the define function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.

            /**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 * @NModuleScope SameAccount
 */

define(['N/file', 'N/sftp', 'N/error'],
function(file, sftp, error) { 
    return {
        beforeLoad: function(){
            var portNumber = -1;
            var connectTimeout = -1;
            var transferTimeout = -1;
            //these variables can be taken as parameters of the script instead

            if (portNumber < sftp.MIN_PORT_NUMBER || portNumber > sftp.MAX_PORT_NUMBER)
                portNumber = sftp.DEFAULT_PORT_NUMBER;
            if (connectTimeout < sftp.MIN_CONNECT_TIMEOUT)
                connectTimeout = sftp.MIN_CONNECT_TIMEOUT;
            else if (connectTimeout > sftp.MAX_CONNECT_TIMEOUT)
                connectTimeout = sftp.MAX_CONNECT_TIMEOUT;

            var connection = sftp.createConnection({
                username: 'sftpuser',
                keyId: 'custkey1',
                url: '192.168.0.100',
                port: portNumber,
                directory: 'inbound',
                timeout: connectTimeout,
                hostKey: "AAAAB3NzaC1yc2EAAAADAQABAAABAQDMifKH2vTxdiype8nem7+lS3x7dTQR/A67KdsR/5C2WUcDipBzYhHbnG6Am12Nd2tlM01LnaBZA6/8P4Y9x/sGTxtsdE/MzeGDUBn6HBlQvgIrhX62wgoKGQ+P2lEAO1+Vz8y3/MB1NmD7Fc62cJ9Mu88YA6jwJOIPZeHYNVyIm9OrY6VyzYyvSJhH0x7SXyvGnijJQF4G8C4c8u/UVpF/sE16xKZtly2Rx0aDL2FsDRtpyPmM602/R6ISbsmgab3MzzAEIu+zLDMdIBJn3cDhNt1F7Rar6Tu0u18KCkk8GPxbnxDuG4sCNOnXPYkDXSMUbM/ocRjYGtqdZUMmeTf3"
            });

            // can also be a big file (created for example by async search)
            var myFileToUpload = file.create({
                name: 'originalname.txt',
                fileType: file.Type.PLAINTEXT,
                contents: 'I am a test file.'
            });

            if (myFileToUpload.size > connection.MAX_FILE_SIZE)
                throw error.create({name:"FILE_IS_TOO_BIG", message:"The file you are trying to upload is too big"});

            var minTransferTimeout = 10;
            if (transferTimeout > connection.MAX_TRANSFER_TIMEOUT)
                transferTimeout = connection.MAX_TRANSFER_TIMEOUT;
            else if (transferTimeout < minTransferTimeout)
                transferTimeout = minTransferTimteout;

            connection.upload({
                directory: 'files',
                filename: 'test.txt',
                file: myFileToUpload,
                replaceExisting: true,
                timeout: transferTimeout
            });
        }
    }; 
}); 

          

General Notices