google a string and count results in typescript

To search Google and count the number of results in TypeScript, we need to make an HTTP request to the Google search page, scrape the HTML response, and extract the number of results from the page. We can use the cheerio library to parse HTML and extract data from it.

Here's an example implementation:

index.ts
import * as http from 'http';
import * as cheerio from 'cheerio';
 
async function getGoogleSearchCount(query: string): Promise<number> {
  const url = `http://www.google.com/search?q=${encodeURIComponent(query)}`;
  const html = await fetchHtml(url);
  const $ = cheerio.load(html);
  const resultStatsText = $('#result-stats').text();
  
  const regex = /(\d+(,\d+)*)/g;
  const match = resultStatsText.match(regex);
  if (match && match.length > 0) {
    const countText = match[0];
    const count = parseInt(countText.replace(/,/g, ''));
    return count;
  }
  
  return 0;
}
 
async function fetchHtml(url: string): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    http.get(url, res => {
      let data = '';
      res.on('data', chunk => {
        data += chunk;
      });
      res.on('end', () => {
        resolve(data);
      });
    }).on('error', err => {
      reject(err);
    });
  });
}

// Example usage:
getGoogleSearchCount('TypeScript tutorial').then(count => {
  console.log(`Found ${count} results.`);
});
1055 chars
41 lines

This code defines a function getGoogleSearchCount that takes a query string, sends an HTTP GET request to Google search, scrapes the HTML response using Cheerio, and extracts the number of results. We first encode the query parameter and form the search URL. Then, we fetch the HTML using the fetchHtml function that returns a promise with the response body. We load the HTML into Cheerio and use a CSS selector #result-stats to extract the result statistics text. We then use a regular expression to extract the first occurrence of a number with commas, remove the commas, and parse the integer. Finally, we return the count.

To test the implementation, we call the getGoogleSearchCount function with a sample query and log the result. Note that this code relies on web scraping and may break if the Google search page layout changes. Also, note that web scraping is against the Google terms of service, so use at your own risk.

gistlibby LogSnag