The readX12 function reads any X12 text, including transaction sets other than 271 responses. Use it on its own for other transaction sets, or to read envelope details such as control numbers.
import { readFile } from 'node:fs/promises';
import { readX12 } from '@ediocracy/parser';
const text = await readFile('response.x12', 'utf8');
const document = readX12(text);
for (const interchange of document.interchanges) {
console.log('Interchange', interchange.header.element(13));
for (const group of interchange.groups) {
console.log(' Group', group.header.element(6), group.header.element(8));
for (const transaction of group.transactions) {
const tags = transaction.segments.map((segment) => segment.tag);
console.log(' Transaction', transaction.header.element(1), tags.join(' '));
}
}
}The document
The readX12 function returns an X12Document object, which has the following properties:
interchanges: each ISA to IEA interchange, in order. One text can contain more than one interchange.findings: problems in text that the parser could still read, such as a control number in a trailer that doesn't match its header.
Each Interchange has its header (ISA), trailer (IEA), delimiters, groups, and any TA1 segments that aren't in a group. Each FunctionalGroup has its header (GS), trailer (GE), and transactions. Each Transaction has its header (ST), trailer (SE), and the segments between them.
Segments
A Segment has a tag, such as EB, and the offset where it starts in the text. It has the following methods:
element(position)returns one element as written. Positions start at 1, soelement(1)ofEB*1**30is1. It returns''for a present but empty element, andundefinedfor a position after the last element.repetitions(position)splits one element on the interchange's repetition separator.
The reader doesn't split composite elements. To get the components, split the result of the element method on interchange.delimiters.component.