Tuesday, June 4, 2019

Find Text in a File Using SuiteScript

At this point in time, Files stored in File Cabinet can only be searched through Global Search or as a sub-criteria of a parent record.  However, contents are not searchable on Global and Saved Searches.  For instance, a user needs to locate a keyword from Text Files, CSV, etc.

This provides a scripting solution to find text from Files using SuiteScript:

     var searchText = 'Lorem ipsum';
     var files = nlapiSearchGlobal('File: %.txt');

     for (var i = 0; files !== null && i < files.length; i++) {
          var fileId = files[i].getId();

          try {
               var file = nlapiLoadFile(fileId);
               var index = file.getValue().toLowerCase().indexOf(searchText.toLowerCase());

               nlapiLogExecution('DEBUG', 'Text ' + (index > 0 ? 'FOUND' : 'NOT found') + ' on File ' + file.getName() + ' (' + fileId + ')');
          } catch(e) {
               nlapiLogExecution( 'DEBUG', 'ERROR While loading File ID: ' + fileId, (e instanceof nlobjError ? e.getCode() + '<br />' + e.getDetails() : e.toString()) );

On Line 2 of the code, indicates to search for files having .txt as the extension name.  This can be changed to .csv, .html, etc. depending on what is needed.

It can be run on any server-side scripts, but it is best to use it on Scheduled Scripts to avoid governance exceeded errors.

Execution Logs shows if the text is found or not in the file on the for loop.

No comments:

Post a Comment