Skip to content

How to loop through series of addresses in a text file and get individual fields in Node.js

I have a text file with multiple addresses in the following format:

335 Ahan St.
Haines City, US 30721

786 Birchmount Dr.
Waterloo, IA 52001

How can I loop through these lines and get individual fields like Street number, street name, city, state, postal code in Node.js

const fs = require('fs');
const readline = require('readline');

const parseAddressFile = path => {
  const data = readline.createInterface({
    input: fs.createReadStream(path)
  });
  
  data.on('line', (line)=> {
    var address1= line.split(" ")[0];
    
    console.log(address1)
  })
};

I’m using readline module and I’m basically stuck after this.

Answer

You can try like this using Regular Expression with named groups as long as you have addresses in the above mentioned format.

const fs = require('fs');
const readline = require('readline');

const parseAddressFile = path => {
  const data = readline.createInterface({
    input: fs.createReadStream(path)
  });

  let address = {};
  const addressList = [];
  data.on('line', (line) => {
    if (line) {
      const temp = line.match(/^((?<streetNumber>d+) (?<streetName>.+)|(?<city>.+), (?<state>[A-Z]+) (?<postalCode>d{5,5}))$/);
      address = Object.keys(temp.groups).reduce((acc, key) => {
        if (temp.groups[key]) {
          acc[key] = temp.groups[key];
        }
        return acc;
      }, address || {});
    } else {
      addressList.push(address);
      address = null;
    }
  }).on('close', function(line) {
    if (address) {
      addressList.push(address);
    }
    console.log(addressList);
  });
};

parseAddressFile('adress.txt')

And the output will be

[
  {
    streetName: 'Ahan St.',
    streetNumber: '335',
    city: 'Haines City',
    postalCode: '30721',
    state: 'US'
  },
  {
    streetName: 'Birchmount Dr.',
    streetNumber: '786',
    city: 'Waterloo',
    postalCode: '52001',
    state: 'IA'
  }
]