HomeAboutProjectsArticles

How to find your current city using Bash or Node.js

January 12, 2020 - 1 min

We look at creating a script, using bash or Node.js, to calculate your current city using the IPinfo API (no sign-up required).

Bash

city=$(curl -s https://ipinfo.io | /usr/local/bin/jq ".city")

All it takes is one line in bash! Notice our use of jq, a lightweight command-line JSON processor, to parse the city name. You can install jq with homebrew: brew install jq.

Node.js

const rp = require('request-promise');

rp('https://ipinfo.io/json').then(res => {
  const json = JSON.parse(res);

  return json.city;
});

We're using request-promise to make the API call using JavaScript, but any similar library or method can be used.

Project Example

This code snippet shows a real-world use of these scripts where the city is used to update the user's status on Slack.

Further Reading

GitHubLinkedInYouTube