Create and Submit an Asynchronous Search Task and Export the Results into a CSV File

The following sample creates an asynchronous search task to execute a saved search and export the results of the search into a CSV file stored in the File Cabinet. After the search task is submitted, the sample retrieves the task status using the task ID. Some of the values in this sample are placeholders. Before using this sample, replace all hard-coded values, such as IDs and file paths, with valid values from your NetSuite account. If you run a script with an invalid value, the system may throw an error.

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/task'], task => {
    // Do one of the following:
    //
    // - Create a saved search and capture its ID. To do this, you can use
    //   the following code snippet (replacing the type, id, filters, and
    //   columns values as appropriate):
    //
    //   let mySearch = search.create({
    //       type: search.Type.SALES_ORDER,
    //       id: 'customsearch_my_search',
    //       filters: [...],
    //       columns: [...]
    //   });
    //   mySearch.save();
    //   let savedSearchId = mySearch.searchId;
    //
    // - Use the ID of an existing saved search. This is the approach that
    //   this script sample uses. Update the following statement with the
    //   internal ID of the search you want to use.
    const savedSearchId = 669;
 
    // Create the search task
    let myTask = task.create({
        taskType: task.TaskType.SEARCH
    });
    myTask.savedSearchId = savedSearchId;
 
    // Specify the ID of the file that search results will be exported into
    //
    // Update the following statement so it uses the internal ID of the file
    // you want to use
    myTask.fileId = 448;
 
    // Submit the search task
    let myTaskId = myTask.submit();
 
    // Retrieve the status of the search task
    let taskStatus = task.checkStatus({
        taskId: myTaskId
    });
 
    // Optionally, add logic that executes when the task is complete
    if (taskStatus.status === task.TaskStatus.COMPLETE) {
        // Add any code that is appropriate. For example, if this script created
        // a saved search, you may want to delete it.
    }
}); 

        

General Notices