N/file Module Script Samples

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

Create and Save a File to the File Cabinet

The following sample shows how to create and save a file to the File Cabinet. In this sample, the folder ID value is hard-coded. For the script to run in the SuiteScript Debugger, you must replace this hard-coded value with a valid folder ID from your account.

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/file'], file => {
    // Create a file containing text
    let fileObj = file.create({
        name: 'testHelloWorld.txt',
        fileType: file.Type.PLAINTEXT,
        contents: 'Hello World\nHello World'
    });
 
    // Set the folder for the file
    // Note that this value is hard-coded in this sample, and you should use
    // a valid folder ID from your account
    fileObj.folder = -15;
 
    // Save the file
    let id = fileObj.save();
 
    // Load the same file to ensure it was saved correctly
    fileObj = file.load({
        id: id
    });
}); 

          

Create a File, Set Property Values, and Save It to the File Cabinet

The following sample shows how to create and save a file to the File Cabinet. It also shows how to set the values of the File.isOnline and the File.folder properties. In this sample, the folder ID value is hard-coded. For the script to run in the SuiteScript Debugger, you must replace this hard-coded value with a valid folder ID from your account.

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/file'], file => {
    // Create a file containing text
    // Note that the folder value is hard-coded in this sample, and you should
    // use a valid folder ID from your account
    let fileObj = file.create({
        name: 'testHelloWorld3.txt',
        fileType: file.Type.PLAINTEXT,
        contents: 'Hello World\nHello World',
        folder: -15,
        isOnline: true
    });
 
    // Save the file
    let id = fileObj.save();
 
    // Load the same file to ensure it was saved correctly
    fileObj = file.load({
        id: id
    });
}); 

          

Create and Save a CSV File then Reload the File and Parse Its Contents

The following sample creates a CSV file, appends several lines of data, and saves the file. The script also loads the file and calculates the total of several values in the file.

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.

            /**
 * @NApiVersion 2.x
 */

require(['N/file', 'N/error', 'N/log'], function (file, error, log) {
    // This sample calculates the total for the
    // second column value in a CSV file.
    //
    // Each line in the CSV file has the following format:
    // date,amount
    //
    // Here is the data that the script adds to the file:
    // 10/21/14,200.0
    // 10/21/15,210.2
    // 10/21/16,250.3

    // Create the CSV file
    var csvFile = file.create({
        name: 'data.csv', 
        contents: 'date,amount\n', 
        folder: 39, 
        fileType: 'CSV'
    });

    // Add the data
    csvFile.appendLine({
        value: '10/21/14,200.0'
    });
    csvFile.appendLine({
        value: '10/21/15,210.2'
    });
    csvFile.appendLine({
        value: '10/21/16,250.3'
    });

    // Save the file
    var csvFileId = csvFile.save();

    // Create a variable to store the calculated total
    var total = 0.0;

    // Load the file
    var invoiceFile = file.load({
        id: csvFileId
    });

    // Obtain an iterator to process each line in the file
    var iterator = invoiceFile.lines.iterator();

    // Skip the first line, which is the CSV header line
    iterator.each(function () {return false;});

    // Process each line in the file
    iterator.each(function (line) {
        // Update the total based on the line value
        var lineValues = line.value.split(',');
        var lineAmount = parseFloat(lineValues[1]);
        if (!lineAmount) {
            throw error.create({
                name: 'INVALID_INVOICE_FILE',
                message: 'Invoice file contained non-numeric value for total: ' + lineValues[1]
            });
        }
        total += lineAmount;
        return true;
    });

    // At the completion of the iteration.each function, the total is 660.5
    
}); 

          

Read and Log File Contents Using Commas and New Lines as Separators

The following sample reads and logs strings from a file using commas and new line characters as separators. This sample can be used as the starting point for a parser implementation.

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 bankStatementParserPlugin
 */

define(['N/file', 'N/log'], function(file, log)   {
    return {
        parseBankStatement: function(context) {
            var reader = context.input.file.getReader();

            var textUntilFirstComma = reader.readUntil(',');
            var next10Characters = reader.readChars(10);
            var textUntilNextNewLine = reader.readUntil('\n');
            var next100Characters = reader.readChars(100);

            log.debug({
                title: 'STATEMENT TEXT',
                details: textUntilFirstComma
            });

            log.debug({
                title: 'STATEMENT TEXT',
                details: next10Characters
            });

            log.debug({
                title: 'STATEMENT TEXT',
                details: textUntilNextNewLine
            });

            log.debug({
                title: 'STATEMENT TEXT',
                details: next100Characters
            })
        }
    }
}); 

          

Read and Log Segments of a File Using a Set of Characters as Separators

The following sample reads and logs segments from a file using a set of characters as separators.

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 bankStatementParserPlugin
 */

define(['N/file', 'N/log'], function(file, log)   {
    return {
        parseBankStatement: function(context) {
            var statementFile = context.input.file;

            var statementSegmentIterator = statementFile.getSegments({separator: '\\|_|/'}).iterator();
            statementSegmentIterator.each(function (segment) {
                log.debug({
                    title: 'STATEMENT TEXT',
                    details: segment.value
                });
                return true;
            });
        }
    }
}); 

          

Copy a File Using Conflict Resolution

The following sample shows how to copy a file in the File Cabinet using the RENAME_TO_UNIQUE conflict resolution option. Using this option, if a file with the same name as the original file already exists in the target folder, the original file is copied and a number is appended to the file name to make the name unique. In this sample, the folder ID values are hard-coded. For the script to run in the SuiteScript Debugger, you must replace these hard-coded values with valid folder IDs from your account.

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.

            /**
 * @NApiVersion 2.x
 */
require(['N/file'], function(file) {
    var fileObj = file.create({
        name: 'test.txt',
        fileType: file.Type.PLAINTEXT,
        contents: 'Hello World\nHello World'
    });
    fileObj.folder = 2667;
    var id = fileObj.save();

    fileObj = file.copy({
        id: id,
        folder: 2670,
        conflictResolution: file.NameConflictResolution.RENAME_TO_UNIQUE
    });
}); 

          

General Notices