Fixed width file handler with TypeScript Decorator
npm install fixed-width-ts-decoratornpm i fixed-width-ts-decoratorInheritance is supported that fields decorated in parent classes will also be included/processed.
``typescript
// class inheritance is Optional here.
export class Transaction extends FixedWidthConvertible {
@FixedWidth({ start: 0, width: 5 })
clientId: string;
@FixedWidth({ start: 5, width: 40 })
parentName: string;
@FixedWidth({ start: 45, width: 40, format: { type: DataType.Float } })
taxAmount: number;
@FixedWidth({
start: 85,
width: 40,
format: {
type: DataType.Float,
precision: 3,
},
})
paymentAmount: number;
@FixedWidth({
start: 125,
width: 20,
format: { type: DataType.Integer },
})
paymentTimeStamp: number;
@FixedWidth({ start: 145, width: 40 })
userId: string;
@FixedWidth({ start: 225, width: 40 })
paymentId: string;
// other non-decorated fields
otherField: string;
}
`
`typescriptFixedWidthConvertible
(() => {
// Or you can read file line by line
const file = fs.readFileSync('data/sample.txt', { encoding: 'utf8' });
const lines = file.split('\n').filter(l => l);
const rs: Array
const trans = new Transaction();
/**
* Option 1: if your domain class extends the abstract class,FixedWidthConvertible
* then you can use the instance.convertFixedWidth method.
*/
trans.convertFixedWidth(line);
/**
* Option 2: if your domain class already extends some other classes
* then use the static function on the class and pass in the instance as argument like below.
*/
// FixedWidthConvertible.convertFixedWidth(line, trans);
return trans;
});
console.log(rs);
})()
``