Parse, validate and generate X12 EDI and HIPAA 5010 files in Node.js: convert X12 to JSON and JSON back to X12, validate 837 claims, 835 remittances, 834 enrollments, 270/271 eligibility, 850 purchase orders, 856 ship notices and 810 invoices, and generate 999 and 997 acknowledgments. Install with npm install edifabric-x12. It runs without an account on the demo serial key.
ediFabric Native is a self-contained, high-performance X12 EDI native shared library. It converts X12 EDI to JSON (and back), validates transaction sets, and generates acknowledgments — callable from any language with a C foreign-function interface (C, C++, Rust, Go, Python, Node.js, Java/JNA, .NET, …). No .NET runtime, JVM, or other dependency is required on the target machine.
Node.js bindings for ediFabric Native, built on the koffi FFI.
| File | Purpose |
|---|---|
edifabric-x12.js |
koffi bindings for the complete C ABI |
edifabric-x12.d.ts |
TypeScript declarations for the bindings |
example_all_functions.js |
runnable walkthrough of every entry point |
c-abi-edifabric_x12_tools.h |
the C header these bindings mirror |
PUBLISHING.md |
how the npm packages are built and published |
npm install edifabric-x12npm also installs the ediFabric Native library for your platform from one of the
@edifabric/x12-<os>-<cpu> packages, so there is nothing else to download. They are
published for Windows x64, Linux x64 and arm64 (glibc 2.34 or later), and macOS
arm64 (12 or later). A library you pass to loadLibrary(path), set in
EDIFABRIC_X12_LIB, or put in the working directory takes precedence over the
bundled one.
- Node.js 18 or later
- koffi, installed with
npm install(prebuilt, no compiler needed) - 64-bit Windows, Linux, or macOS
- The native library for your platform (installed from npm with the package; download it when you run from a clone):
| Platform | File |
|---|---|
| Windows | edifabric-x12-tools.dll |
| Linux | edifabric-x12-tools.so |
| macOS | edifabric-x12-tools.dylib |
- Evaluate with the demo serial key
bd96a836feca45cb91c86ee65d281f52without creating an account. It works for ediFabric Native, .NET and Cloud, and has a limited quota. Once it runs out, sign up free for Community to get your own evaluation serial key. Community never expires, requires no credit card, and is for non-production use. The first 14 days after you subscribe have unlimited operations, then the quota is 250 per day. To extend the unlimited period, ask through the support portal or at support@edifabric.com. After signup, retrieve your serial from Your Account. - Download the ediFabric Native library.
Plus your model files (per transaction set) and a map file that tells the engine where to find them. See Model map for details.
Use the demo serial key bd96a836feca45cb91c86ee65d281f52, which needs no account, or sign up free for Community at
edifabric.com/pricing to get your own evaluation serial key.
Then download the library from
here.
Put the native library beside edifabric-x12.js, install the dependency, then run the walkthrough with your serial:
npm install
node example_all_functions.js --serial bd96a836feca45cb91c86ee65d281f52It authorizes with your Community (or paid) serial, loads the model map, and calls every function in the ABI, printing what each one returns.
======================================================================
Parse: parse (mode 2, JSON + validation report)
======================================================================
8711 chars total, validation starts at offset 8556
validation -> {"errors":[{"index":9,"element_index":2,"composite_index":1,"repetition_index":1,"code":17,"message":"Invalid EDI code"}],"errors_count":1,"data_count":46}
Options:
node example_all_functions.js --serial YOUR_SERIAL # Community or paid serial (required)
node example_all_functions.js --lib /opt/edifabric # library file or folderYou can also set EDIFABRIC_SERIAL instead of passing --serial.
The library path is resolved from --lib, then EDIFABRIC_X12_LIB, then the
module folder, its parent, the working directory, and the library bundled in the
@edifabric/x12-<os>-<cpu> package. The serial comes from
--serial, then EDIFABRIC_SERIAL.
All strings and payloads cross the boundary as UTF‑8 byte buffers
(pointer + length). Every function returns 0 on success or a non-zero
error code.
const fs = require('fs');
const ef = require('./edifabric-x12'); // or: import ef from './edifabric-x12.js';
const serial = 'your-serial'; // from your Community or paid plan
ef.loadLibrary(); // or ef.loadLibrary('C:\\libs\\edifabric-x12-tools.dll')
ef.ensureToken(serial, 3600); // every plan: license the process (see Licensing)
ef.setMap(JSON.stringify({ default: serial, maps: {} }));
const edi = fs.readFileSync('purchase-order.edi');
const { output: transactions } = ef.parse(edi, ef.ParseMode.JSON);
console.log(transactions);Inputs accept a string or a Buffer (any TypedArray or ArrayBuffer also works).
Read a file from a subfolder of the script:
const path = require('path');
const edi = fs.readFileSync(path.join(__dirname, 'edi', '837p.txt'));parse returns { output, offset }. In modes 2 and 3, offset marks where the
validation and acknowledgment JSON starts inside the output. It is a string index,
so output.slice(offset) is safe even when the data contains non-ASCII characters.
const config = JSON.stringify({
validate: { snip_level: 2, max_errors: 0 },
ack: { gen997: false, supress_ta1: false },
});
const { output, offset } = ef.parse(edi, ef.ParseMode.JSON_VALIDATE_ACK, config);
const transactions = output.slice(0, offset);
const report = JSON.parse(output.slice(offset));
console.log(report.errors_count, report.ack);| Mode | Constant | Output |
|---|---|---|
| 1 | ParseMode.JSON |
transaction-set JSON |
| 2 | ParseMode.JSON_VALIDATE |
JSON plus a validation report |
| 3 | ParseMode.JSON_VALIDATE_ACK |
JSON plus validation and a 999/997/TA1 acknowledgment |
iterSplit streams one transaction set (or repeating loop) at a time with flat
memory use. segment_id must be ST or the first segment of a repeating loop.
const config = JSON.stringify({ split: { segment_id: 'LX', segment_depth: 6, loop_id: '2400' } });
for (const { payload, offset, isLast } of ef.iterSplit(edi, ef.ParseMode.JSON, config)) {
handle(JSON.parse(payload.toString('utf8')));
}iterMerge streams a full interchange JSON document back out one segment at a time:
const out = fs.openSync('out.edi', 'w');
for (const segment of ef.iterMerge(transactions)) {
fs.writeSync(out, segment);
fs.writeSync(out, '\r\n');
}
fs.closeSync(out);Both wrap the underlying startSplit/split/getResult and
startMerge/merge/getResult sequences, which you can also drive directly.
const ediText = ef.build(transactions, '\r\n'); // postfix null for compact outputConventions used by every function:
- Returns
int:0= success, non-zero = error code. - Inputs are UTF‑8
byte*+int length. - Output functions use grow-and-retry: if the buffer is too small the call
returns
1(InsufficientCapacity) and writes the required size into the length out-parameter; reallocate and call again. - Exceptions never cross the boundary.
Every wrapper throws EdiFabricError when the native call returns a non-zero
status; it carries code, nativeMessage, and api (the C function name).
Buffer growth (InsufficientCapacity) is retried automatically. The wrappers use
camelCase names; the C functions keep their ABI names on loadLibrary().raw.
| Group | Functions |
|---|---|
| Loading | loadLibrary |
| Lifecycle | initLogger, shutdownLogger, clearCache |
| Licensing | ensureToken, getAppVersion, getToken, validateToken, setToken, getTokenExpiration, setSerial |
| Model map | setMap |
| Processing | parse, startSplit, split, build, startMerge, merge, getResult |
| Errors | getError, freeError, decodeString, check |
| Wrappers | iterSplit, iterMerge |
| Constants | ParseMode, LogLevel, ErrorCode, EdiFabricError |
getError frees the native string for you. Call freeError only if you
invoke the raw export yourself (loadLibrary().raw.get_error(code) returns a
pointer; read it with decodeString). Builds that do not export free_error fall
back to the C runtime free.
getTokenExpiration returns a BigInt, because .NET ticks don't fit in a
JavaScript number. getResult, iterSplit, and iterMerge return Buffers;
call .toString('utf8') for text.
Note
You can evaluate with the demo serial key bd96a836feca45cb91c86ee65d281f52
without creating an account. It works for ediFabric Native, .NET and Cloud. Once the limited
quota for this provisional key runs out, an account and a Community subscription are required
to continue the evaluation.
Sign up free for the Community plan to get your own evaluation serial key. Community never expires, requires no credit card, and is for non-production evaluation, learning, and prototyping (unlimited operations for the first 14 days after you subscribe, then 250 per day; to extend the unlimited period, ask through the support portal or at support@edifabric.com). After signup, copy your serial from Your Account.
If you hit the Community daily quota, native calls return error 639; upgrade at edifabric.com/pricing if you want to continue.
Use ensureToken on every plan. Since ediFabric Native 1.2.0 it's the one licensing call for Community, Developer,
Enterprise and Perpetual, in place of setSerial. Call it once at startup with your serial and the number of seconds a
token must still be valid, and it keeps the process licensed from then on.
| Plan | What ensureToken does |
|---|---|
| Community and the demo serial | Checks the serial online on every operation, as setSerial does |
| Developer, Enterprise and Perpetual | Gets a token, caches it on disk and refreshes it before it expires, so operations are checked locally |
The token cache is %LOCALAPPDATA%\EdiFabric\tokens on Windows, ~/Library/Caches/EdiFabric/tokens on macOS, and
$XDG_CACHE_HOME/edifabric/tokens (or ~/.cache/edifabric/tokens) on Linux, so every process on the machine reuses
the token. Set EDIFABRIC_TOKEN_CACHE to another folder, or to none to turn the cache off. When the license server
can't be reached, a cached token that's still valid keeps working; without one, calls return error 640.
// Every plan (recommended): license the process; tokens are refreshed when they expire within N seconds
ef.ensureToken(serial, 3600);
console.log(ef.getTokenExpiration()); // .NET UTC ticks as BigInt, 0n when unset
// Enterprise and Perpetual, when your hosts manage tokens themselves: fetch / validate / set an offline token
const token = ef.getToken(serial);
ef.validateToken(token);
ef.setToken(token);setSerial still works, but it checks the serial online on every operation, on every plan. setToken is for Enterprise and
Perpetual hosts that fetch and distribute offline tokens themselves.
Self-service offline tokens last 30 days, so refresh them before they expire. If your hosts can't refresh a token, Enterprise and Perpetual can request a 1-year token, and Perpetual gets a new one free every year, if approved. Long-lived tokens are issued after the trial or evaluation period to registered companies using professional email addresses, and are non-refundable once issued. See how to request one. Treat every token as a secret, and keep it out of source control.
setMap tells the engine where to find transaction-set models. Keys are
message:version. Set default to your serial to resolve unmapped transaction
sets through the online spec service, or leave it null (or "") and map
everything locally.
The example builds that JSON at runtime instead of hard-coding paths. Online
fallback is an object with default set to your serial:
ef.setMap(JSON.stringify({ default: serial, maps: {} }));For local models, load a map file and rewrite each entry's location to the
folder that actually holds the JSON files (see loadLocalMap in
example_all_functions.js):
const mapPath = path.join(__dirname, 'map', 'map.json');
const localMap = JSON.parse(fs.readFileSync(mapPath, 'utf8'));
for (const entry of Object.values(localMap.maps || {})) {
entry.location = path.dirname(mapPath);
}
ef.setMap(JSON.stringify(localMap));map.json lists each transaction set; location is filled in at runtime so the
same file works from any working directory:
{
"default": "",
"maps": {
"837:005010X222A1": { "type": 1, "name": "model837P.json", "location": "" },
"834:005010X220A1": { "type": 1, "name": "model834.json", "location": "" }
}
}You can also mix both: keep default as your serial and add local entries under
maps for the transaction sets you ship on disk.
All X12 transactions, such as 837P, 834 and 850, are represented as ediFabric Native JSON models. The models are the same on every plan, Community or paid.
Standard models come from the EDI spec library. Open the transaction, for example 837P, and under Download select Native model. Downloads need a free sign-in, as the Community plan is enough, and accepting the license agreement once; every plan includes 50 spec downloads a day. The specs the public examples use, such as 837P, 834, 835, 850 and 810, are a free sample that downloads without signing in. To parse, you don't need to download standard models at all: with default set to your serial, the engine gets them from the online spec service.
Custom models come from the EDI Spec Builder, which you use signed in to your free account. When a trading partner changes the standard, open the transaction in the EDI spec library and select Customize in Spec Builder, or import your own OpenEDI file. Edit the OpenEDI schema until it matches the partner's guide and select Update. Then, on the ediFabric Native tab, select Download Native.
Save the downloaded file where the map can name it, and add it to maps under its message:version key, for example 837:005010X222A1. The file is the compiled layout the engine loads, not the OpenEDI schema. To change a model, edit the spec in the EDI Spec Builder and download it again. See EDI models and OpenEDI format.
All JSON uses snake_case keys and is case-insensitive.
{
"validate": { "regex": null, "date_format": null, "time_format": null,
"skip_seq_count": false, "skip_hl_seq": false,
"snip_level": 0, "max_errors": 0 },
"ack": { "supress_ta1": false, "ak901p": false,
"gen_for_valid": false, "gen997": false }
}validate— applied whenmode ≥ 2;snip_levelis1–4.ack— applied whenmode == 3.
All sections are optional for parse.
{
"split": { "segment_id": "ST", "segment_depth": 0, "loop_id": null }
}split— required forstartSplit.
Splitting is possible for the following boundaries:
- Transaction - for files that contain batches of transactions.
- Repeating loop - for files that contain batches of loops, such as order lines, claims or benefit enrollments.
The splitter must be configured as follows:
segment_id— the name of the segment to split by. It must be either ST or the first segment in the repeatable loop (Mandatory).segment_depth— the depth of the segment in the model hierarchy (Mandatory).loop_id— the name of the loop for the segment specified in segment_id (Optional).
The values for the splitter are in EdiNation, the free X12 editor. Load a file, select Parse, and select the first segment of the loop in the Structure tab. For example, to split an 837P by loop 2000A, load the 837P sample from Samples and select the HL segment in loop 2000A. Under Selected item, segment_id is Code, loop_id is the last item in Path, and segment_depth is Depth.
Note
If a segment shows no Splitter, the file can't be split by that segment.
The easiest way to get the splitter configuration is to select the copy button next to Splitter, which copies the three values as JSON. Paste them as the value of split.
The calls are synchronous and run on the calling thread. The library holds
process-global state (model map, active split reader, active merge writer, last
result, license) behind an internal lock. parse and build are independent per
call, but each split or merge sequence must run to completion without another
split or merge interleaving from a different thread. Each worker_threads worker
shares the same process-global state.
0 is success and 1 means the output buffer was too small. Library-level codes
are exposed as ErrorCode, and getError(code) returns the message.
Validation codes (elements, segments, transaction sets, groups, and interchanges)
appear in the parse report when mode ≥ 2.
Error 639 means the Community (evaluation) daily quota was exceeded. Upgrade your plan at edifabric.com/pricing if you wish to continue.
| Code | Meaning |
|---|---|
| 1 | The suggested output buffer size is too small |
| 501 | Unexpected error. Contact support@edifabric.com and include a sample project/file to reproduce the issue |
| 502 | No connection to EdiNation API |
| 503 | The model map configuration is invalid. Check the paths and the model file names are correct |
| 611 | The input buffer is either null or its size is nill |
| 612 | The logger failed to log |
| 613 | The map configuration file is invalid |
| 614 | The output capacity must be positive |
| 615 | Models map must be set before parsing or splitting |
| 616 | Mode must be any of: 1 - Parse, 2 - Parse and Validate, 3 - Parse and Validate and Acknowledge |
| 617 | Parser failed. Contact support@edifabric.com and include a sample project/file to reproduce the issue |
| 618 | Validation failed. Contact support@edifabric.com and include a sample project/file to reproduce the issue |
| 619 | Validation serializer failed. Contact support@edifabric.com and include a sample project/file to reproduce the issue |
| 620 | The token is invalid. Contact support@edifabric.com for assistance |
| 621 | The configuration file is invalid |
| 622 | The split segment ID must not be blank |
| 623 | Call startSplit before splitting |
| 624 | The result can't be retrieved. Contact support@edifabric.com and include a sample project/file to reproduce the issue |
| 625 | Result buffer size mismatched |
| 626 | Call startMerge before merging |
| 627 | The output buffer is either null or its size is nill |
| 628 | The serial number is missing or incorrect. getToken doesn't work with Developer license |
| 629 | License was not installed. Contact support@edifabric.com for assistance |
| 630 | No license to use this version. Contact support@edifabric.com for assistance |
| 631 | The token has expired. Get and set a new token to continue |
| 632 | The token is missing. Set token to continue |
| 633 | Reached the maximum number of licenses. Set token to continue |
| 634 | Environment not recognized for licensing or reached the maximum number of licenses |
| 635 | Serial or token not found. Either set token or serial to continue |
| 636 | The rate to get serials was exceeded for your license. Wait for 60 seconds and try again or upgrade your license |
| 637 | Invalid JSON. Enable logging for additional details |
| 638 | The operation is not supported by your license |
| 639 | Community daily quota exceeded. Your license has reached its daily call limit. Upgrade your plan at edifabric.com to continue |
| 640 | The license server can't be reached and no valid token is cached. Check the internet connection, firewall and proxy settings, and try again. Contact support@edifabric.com if this continues |
Error: Could not load edifabric-x12-tools.dll — the library is
not on any searched path. Pass ef.loadLibrary('/path/to/library') or set
EDIFABRIC_X12_LIB. If the message ends with Cannot find function ... in shared library,
the library is older than these bindings; download the current build.
Cannot find module 'koffi' — run npm install in this folder.
Error 615 on parse — call setMap before parsing or splitting. clearCache
resets the map, so reload it afterwards.
Error 628 / 635 on parse — license the process first with ensureToken, on any plan, or with setToken and an offline token.
Error 633 on ensureToken / getToken — the plan's machine quota is used up. Contact support.
Error 639 — the Community (evaluation) daily quota was exceeded. Wait until the next day, or upgrade your plan if you wish to continue.
Error 640 — the license server can't be reached and no valid token is cached. Check the internet connection, firewall and proxy settings. A cached token that's still valid keeps working, so this happens only before the first token, or after a token expired.

