await-emoji.js 1.89 KB
// The node-fetch package provides a fetch() function for Node.js.
// Like in a browser, this makes a Promise for an HTTP request.
// You can install it using `npm install node-fetch`.
const fetch = require('node-fetch')

const README_URL = 'https://unicode.org/Public/zipped/latest/ReadMe.txt'
const UNICODE_FILE = 'UnicodeData.txt'

// Gets the Unicode number ("code point") for the character with a given name
async function getUnicodeNumber(searchName) {
  // Fetch the readme to determine the latest Unicode version (e.g. 13.0.0)
  const readmeResponse = await fetch(README_URL)
  const readme = await readmeResponse.text() // read readme as a string
  // The last line of the readme contains the current Unicode URL,
  // e.g. https://www.unicode.org/Public/13.0.0/ucd/
  const [latestURL] = readme.trim().split('\n').slice(-1)

  // Then fetch the list of Unicode characters
  const charactersResponse = await fetch(latestURL + UNICODE_FILE)
  const charactersData = await charactersResponse.text()
  // Each line of the data file corresponds to one Unicode character
  for (const characterData of charactersData.trim().split('\n')) {
    // Each line has several fields separated by `;`.
    // The first is the character's number and the second is its name.
    const [characterNumber, characterName] = characterData.split(';')
    if (characterName.toLowerCase() === searchName) {
      // If this is the requested character, read its number in base-16
      return parseInt(characterNumber, 16)
    }
  }
  return undefined
}

// Prints the Unicode character with the given name (e.g. `pile of poo`)
async function printUnicode(searchName) {
  // getUnicodeNumber() returns a Promise, so we need to await it
  const number = await getUnicodeNumber(searchName)
  // Convert the Unicode number to a character
  if (number !== undefined) console.log(String.fromCodePoint(number))
}

// Prints 💩
printUnicode('pile of poo')