I am trying to solve this problem where I have to read the text files as an input and create object array with Node.js. The only corner cases are there are extra white spaces.
Input:
89 Westport Ave.
Pembroke Pines, FL 33028
9529 Bayport Rd.
Eau Claire, WI 54701
9957 Wakehurst Street
Suite 42
Bonita Springs, FL 34135
8233 Franklin Drive
Neenah, WI 54956
Output:
[ {
address1: '89 Westport Ave.',
address2: null,
city: 'Pembroke Pines',
state: 'FL',
zip: '33028' },
{
address1: '9529 Bayport Rd.',
address2: null,
city: 'Eau Claire',
state: 'WI',
zip: '54701' },
{
address1: '9957 Wakehurst Street',
address2: 'Suite 42',
city: 'Bonita Springs',
state: 'FL',
zip: '34135' },
{
address1: '8233 Franklin Drive',
address2: null,
city: 'Neenah',
state: 'WI',
zip: '54956' }]
Code I am trying:
const parseAddressFile = path => {
const fs = require('fs');
const readline = require('readline');
const data = readline.createInterface({
input: fs.createReadStream(path)
});
let address = {address1: "",
address2: "",
city: "",
state: "",
zip: ""};
const addressList = [];
data.on('line', function (line) {
line = line.trim();
addressList.push(line);
// console.log(addressList);
});
function line2() {
var lines = addressList.split(',');
return lines;
}
// console.log(line2());
data.on('close', function (line) {
// array console.log(addressList);
// var Ncount = 0;
for(var x =0; x < addressList.length; x++){
// console.log(address);
// console.log(addressList[0]);
address['address1'] = addressList[x];
if (addressList[x].match('Suite 42')){
address['address2'] = 'Suite 42';
}else{
address['address2'] = null;
}
// address['address2'] = null;
address['city'] = addressList[line2(x)];
address['state'] = addressList[x];
address['zip'] = addressList[x];
console.log(address);
}
});
};
module.exports = parseAddressFile;