How to Validate and Look Up Phone Numbers from a CSV file

In this guide, we will validate phone numbers from a CSV file using Node.js and the Lookups API.

Note: If you would like to learn more about the Lookups API, visit our product page.

Getting started

In order to work through this tutorial, you need:

Helpful resources

Get the code

All the code for this tutorial is available in the Lookups CSV Tutorial Github repo.

 

Step 1 – Create a CSV file

Let’s create the csv file which we will contain the numbers we would like to lookup.
To do this, go to your Desktop and create a folder called “Lookups”. Inside this folder, create a csv file called “Numbers”. Open this csv file and in the first row of the first column, type in Number and add the phone numbers under this column. These numbers should be valid or else the lookup will fail.

 

Step 2 – Initialise project

Before we can start writing any code, we need to initialise our project. Open up command line from the root directory of your project (lookups) and run “npm init”. You can leave the options blank and press “Enter” when prompted with “Is this ok? (yes)”

 

Step 3 – Install modules

To keep our script concise, we’ll use a few essential third-party modules – csv-parser, request and fs. request is a handy module to make HTTP calls. csv-parser takes in csv and gets the rows out as object. fs is the Node.js file system module that allows you to work with the file system (prebuilt into Node). To install the other modules, run the following commands separately on your command line:

npm install request
npm install csv-parser

 

Step 4 – Read data from csv

We’ll write our code in a file called index.js and save this file in the Lookups folder.

Let’s take a look at how we can read data from the csv file:

var csv = require('csv-parser');
fs.createReadStream('numbers.csv')
  .pipe(csv())
  .on('data', function (data) {
      console.log(data.Number);
});

An example of the output:

 

Step 5 – Authentication and lookup number

To lookup a number, you need to make a call to the Lookups API and you’ll need to use your credentials for authentication.

var request = require('request');

// Replace key and secret with your own credentials
var key = "xx";
var secret = "yy";
var auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");

function lookup(number){
    var url = "https://api.messagemedia.com/v1/lookups/phone/"+number+"?options=carrier%2Ctype";
    request({
            url : url,
            headers : { "Authorization" : auth }
        },
        function (error, response, body) {
            var phone_number = JSON.parse(body)["phone_number"]
            var type = JSON.parse(body)["type"];
            var carrier = JSON.parse(body)["carrier"]["name"];
            var country_code = JSON.parse(body)["country_code"];
            console.log(phone_number + " " + type + " " + carrier + " " + country_code);
        }
    );
}

 

Step 6 – Add headers before writing to file

Our output csv file does not contain any headers, so we will need to add some in. Make sure to call the function before you start looking up numbers, so the output file is already created with the headers.

function createFile(){
  var dataToWrite = "Phone Number,Type,Carrier,Country Code\n";
  fs.writeFile('results.csv', dataToWrite, 'utf8', function (err) {
    if (err) {
      console.log('Some error occured - file either not saved or corrupted file saved.');
    } else{
      console.log('File created and headings added.');
    }
  });
}

 

Step 7 – Write to file

function writeToFile(phone_number, type, carrier, country_code) {
  var dataToWrite = phone_number+","+type+","+carrier+","+country_code+"\n";
  fs.appendFile('results.csv', dataToWrite, 'utf8', function (err) {
    if (err) {
      console.log('Some error occured - file either not saved or corrupted file saved.');
    } else{
      console.log('Lookups information added successfully.');
    }
  });
}

 

Step 8 – Putting it all together

We’ve cleaned up our code and made it look modular.

var csv = require('csv-parser');
var fs = require('fs');
var request = require('request');

var key = "xx";
var secret = "yy";
var auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");

// Entry point
start();

function start(){
  // Create file and insert headers
  createFile();
  // Read numbers from file and perfom lookup on each function
  fs.createReadStream('numbers.csv')
    .pipe(csv())
    .on('data', function (data) {
        lookup(data.Number);
    });
}

// Make call to Lookups API and return data to writeToFile function
function lookup(number){
  var url = "https://api.messagemedia.com/v1/lookups/phone/"+number+"?options=carrier%2Ctype";
  request({
          url : url,
          headers : { "Authorization" : auth }
      },
      function (error, response, body) {
          var phone_number = JSON.parse(body)["phone_number"]
          var type = JSON.parse(body)["type"];
          var carrier = JSON.parse(body)["carrier"]["name"];
          var country_code = JSON.parse(body)["country_code"];
          writeToFile(phone_number, type, carrier, country_code);
      }
  );
}

// Fill in the lookup details of the number in the csv file
function writeToFile(phone_number, type, carrier, country_code) {
  var dataToWrite = phone_number+","+type+","+carrier+","+country_code+"\n";
  fs.appendFile('results.csv', dataToWrite, 'utf8', function (err) {
    if (err) {
      console.log('Some error occured - file either not saved or corrupted file saved.');
    } else{
      console.log('Lookups information added successfully.');
    }
  });
}

// Create and add headers to the file
function createFile(){
  var dataToWrite = "Phone Number,Type,Carrier,Country Code\n";
  fs.writeFile('results.csv', dataToWrite, 'utf8', function (err) {
    if (err) {
      console.log('Some error occured - file either not saved or corrupted file saved.');
    } else{
      console.log('File created and headings added.');
    }
  });
}

 

Step 9 – Run the tutorial

Run node index from the root directory. In this example, we only have one number in the numbers.csv file.

Conclusion

That’s it! You can now lookup numbers from a csv file and output the details into a separate file.