google-apps-scriptbyte-order-markcreatefile

Create text file without BOM google apps script


I am trying to create a text file in Google Drive that will be read by another program for automation. However, if I create the text file by Google Script the text will have BOM, which make automation quite unreliable. I am currently using

var textFile = jobFolder.createFile(aFileName, fileContent,MimeType.PLAIN_TEXT)
var textFile = jobFolder.createFile(aFileName, fileContent)

What's the way to create text file without BOM with Google App Script?


Solution

  • At the BOM data of UTF-8, EF BB BF is added to the top of data. In this case, I think that to remove the top 3 bytes is to achieve your goal. So how about the following modification?

    From:

    var textFile = jobFolder.createFile(aFileName, fileContent,MimeType.PLAIN_TEXT)
    

    To:

    var [,,,...newData] = Utilities.newBlob(fileContent).getBytes();
    var blob = Utilities.newBlob(newData, MimeType.PLAIN_TEXT, aFileName);
    var textFile = jobFolder.createFile(blob);
    

    Note:

    References:

    Added:

    From your following replying,

    I have error on this line var [,,,...newData] = Utilities.newBlob(fileContent).getBytes();. Maybe because my Google App Script is the older version. What can I try for this?

    I understood that you are not using V8 runtime. In this case, how about the following script?

    Sample script:

    var newData = Utilities.newBlob(fileContent).getBytes();
    newData.splice(0, 3);
    var blob = Utilities.newBlob(newData, MimeType.PLAIN_TEXT, aFileName);
    var textFile = jobFolder.createFile(blob);