Problems trying to read a file from an attachment on an Ontology object

I have a typescript function where I am trying to read a file from an attachment on an Ontology object.

I can do this with Excel’s by having:

import * as XLSX from 'xlsx';

and

            const attachmentData: Blob = await doc.attachment!.readAsync();

            // Convert the Blob to an ArrayBuffer
            const arrayBuffer = await attachmentData.arrayBuffer();

            const workbook = XLSX.read(arrayBuffer, { type: 'buffer'});

But I can’t seem to do the equivalent with a plain text file that is actually a tab delimited file of records.

I am trying (based on guidance from AIP Assist):

            const attachmentData: Blob = await doc.attachment!.readAsync();

            // Convert the Blob to an ArrayBuffer
            const arrayBuffer = await attachmentData.arrayBuffer();

            // Convert ArrayBuffer to string
            const textDecoder = new TextDecoder("utf-8");
            const tabDelimitedData = textDecoder.decode(arrayBuffer );

But I’m getting problems because TextDecoder is not natively available in the platform.

From Googling around i see a library @types/text-encoding which should be a good Polyfill to allow use of TextDecoder, but I can’t get it to work.

Trying to import it with

import { TextDecoder } from '@types/text-encoding';

give a compile error: Module not found: Error: Can't resolve 'text-encoding'.

importing with

import { TextDecoder } from 'text-encoding';

fixes the compile error but gives a runtime error of Module not found: Error: Can't resolve 'text-encoding'.

Overall, I am stumped as to how I should read a simple text file as an ontology attachment via Typescript. Am I over complicating it?

Any advice welcome, please.

Hello

You should be able to read file contents through .text() method on Blob type: const text = await attachmentData.text()

As for the other issue, you can use the Libraries section (on the left of the Code Repositories editor) to install @types/text-encoding.

Good luck!

@Yurii.Mashtalir’s suggestion to use .text() for UTF-8 encoded data should work and is the approach I would recommend.

As for trying to polyfill TextDecoder, @types/text-encoding is just the type definitions for the text-encoding package. You need to take a dependency on the actual implementations to use them in your code. Unfortunately the text-encoding package is long abandoned by now. You could instead use @zxing/text-encoding which is a widely-used fork of the text-encoding package.

Thank you @Yurii.Mashtalir and @jedboffey .
That worked a treat. I knew i was over complicating it.
Thanks a lot for the quick and thorough feedback.