Skip to content

Instantly share code, notes, and snippets.

@etherealite
Created May 21, 2017 21:16
Show Gist options
  • Save etherealite/df1dc47d4422cfce67b43400cbb2099e to your computer and use it in GitHub Desktop.
Save etherealite/df1dc47d4422cfce67b43400cbb2099e to your computer and use it in GitHub Desktop.
const fs = require('fs');
const file = fs.readFileSync('contacts.rtf', 'utf8');
const matches = file.match(/\n[a-z ]+.* 0 Y(?:\n.+)+/gi);
const contacts = matches.map(match => {
const lines = match.split("\n");
const contact = Object.create({});
contact.account = lines[1].slice(0, 7);
contact.store = lines[1].slice(8, 11);
contact.t = lines[1].slice(13, 14);
contact.name = lines[1].slice(15, 38);
contact.street2 = lines[1].slice(39, 62);
contact.phone = lines[1].slice(62, 74);
contact.sm = lines[1].slice(90,92);
contact.c = lines[1].slice(93, 94);
contact.tc = lines[1].slice(96, 98);
contact.enterd = lines[1].slice(99, 105);
contact.LShip = lines[1].slice(106, 112);
contact.YTDShip = lines[1].slice(114, 124);
contact.street = lines[2].slice(15, 39);
contact.GLN = lines[2].slice(39, 62);
contact.city = lines[3].slice(15, 36);
contact.state = lines[3].slice(36, 38);
contact.zip = lines[3].slice(39, 46);
contact.fax = '';
contact.contact = '';
contact.misc = '';
if (lines.length > 4) {
contact.fax = lines[4].slice(39, 59);
contact.contact = lines[4].slice(59, 88);
contact.misc = lines[4].slice(88, 117);
}
for (let key in contact) {
contact[key] = contact[key].trim();
}
return contact;
});
const header = Object.keys(contacts[0]).reduce((obj, key) => {
obj[key] = key;
return obj
}, {});
const withHeader = [header].concat(contacts);
const CSVLines = withHeader.map(contact => {
//const escapes = [',', '\r', '\n' '"'];
const fields = Object.keys(contact).map(key => {
const raw = contact[key];
const quoteEsc = raw.replace('"', '""');
const fullEsc = quoteEsc.match(/(,|\r|\n|")/) ? '"' + quoteEsc + '"' : quoteEsc
return fullEsc;
});
const line = fields.join(',');
return line;
});
const CSV = CSVLines.join("\r\n");
console.log(CSV);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment