I am attempting to create a historical csv backup (appended rather than overwritten) to our file cabinet using a saved searches results (on a once a week schedule).
I know its possible to write a saved searches results to a CSV (using task), but I'm not sure how I can append instead (maybe using file.appendline?). Here is what I've come up with which results in the appended data being "task.SearchTask" instead of the saved search results:
/**
* @NApiVersion 2.1
* @NScriptType ScheduledScript
*/
define(['N/file', 'N/task'],
/**
* @param{file} file
* @param{task} task
*/
(file, task) => {
/**
* Defines the Scheduled script trigger point.
* @param {Object} scriptContext
* @param {string} scriptContext.type - Script execution context. Use values from the scriptContext.InvocationType enum.
* @since 2015.2
*/
//[file ID, Saved Search ID]
const keys = [
[72567, 1701]
]
const execute = (scriptContext) => {
for(var i = 0; i < keys.length; i++) {
var searchTask = task.create({
taskType: task.TaskType.SEARCH,
savedsearchId: keys[i][1]
});
var csvFile = file.load({
id: keys[i][0]
});
//This probably doesn't work...
csvFile.appendLine({
value: searchTask
});
csvFile.save();
}
}
return {execute}
});
Any assistance would be appreciated!
The issue you're encountering is because task.create()
doesn't directly return the results of the saved search; instead, it returns a SearchTask
object representing the background task. You need to execute the search, fetch the results, and append them to the CSV file. Here's a corrected approach:
Use task.create()
to initiate the search task.
Retrieve the saved search results using search.run()
or
search.runPaged()
.
Append the results to the CSV file.
/**
* @NApiVersion 2.1
* @NScriptType ScheduledScript
*/
define(['N/file', 'N/search', 'N/task', 'N/log'],
(file, search, task, log) => {
const keys = [
[72567, 1701] // File ID, Saved Search ID
];
const execute = (scriptContext) => {
keys.forEach(([fileId, savedSearchId]) => {
// Load the CSV file from the file cabinet
var csvFile = file.load({
id: fileId
});
// Create a search object using the saved search ID
var searchObj = search.load({
id: savedSearchId
});
// Run the search and get the results in pages to avoid memory issues
var pagedResults = searchObj.runPaged({
pageSize: 1000 // Adjust as needed
});
pagedResults.pageRanges.forEach(function (pageRange) {
var page = pagedResults.fetch({
index: pageRange.index
});
page.data.forEach(function (result) {
var csvLine = result.columns.map(col => result.getValue(col)).join(',');
csvFile.appendLine({
value: csvLine
});
});
});
// Save the appended CSV file back to the file cabinet
csvFile.save();
});
};
return { execute };
});