Return a File with Alternative Character Encoding
By default, Suitelet textual responses are encoded using UTF-8 encoding.
In SuiteScript 1.0, you can construct a response with an alternative encoding by using the nlobjResponse.setEncoding()
function. However, there is no direct equivalent for this function in SuiteScript 2.x.
To return a file with an alternative encoding in SuiteScript 2.x, you can use the following modules:
-
N/file Module – Use file.create(options) to create a file with a character encoding other than UTF-8.
-
N/https Module – Use ServerResponse.setHeader(options) to specify the same character encoding in the
charset
parameter of the Content-Type header. Then, call ServerResponse.writeFile(options) to return the file in the response. This method preserves the file's encoding if thecharset
value specified in the header matches the file's encoding.
The following script sample shows how to create a file with an encoding other than UTF-8, and return the file through a Suitelet response with the file's encoding preserved.
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.0
* @NScriptType Suitelet
*/
define(['N/https', 'N/file'], function(https, file)
{
function onRequest(context)
{
var outputFile = file.create({
name: "virtual.txt",
contents: "This response is encoded in iso-8859-1 -- éáíóú",
fileType: file.Type.PLAINTEXT,
encoding: file.Encoding.ISO_8859_1
});
// Charset in Content-Type header must match the file's encoding.
context.response.setHeader("Content-Type", "text/plain;charset=iso-8859-1");
context.response.writeFile(outputFile, true);
}
return {
onRequest: onRequest
};
});