### Install xchange-rates Package Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/quick-start.md Install the library using npm. This is the first step before using it in your project. ```bash npm install xchange-rates ``` -------------------------------- ### Install xchange-rates with yarn Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/README.md Use this command to add the package to your Node.js project dependencies if you are using yarn. ```bash yarn add xchange-rates ``` -------------------------------- ### Example: Fetching Rates from Local Cache Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/configuration.md Shows how to use the `xchangerate` function with `useCDN` set to `false` to read currency rates from a local cache file. ```javascript const result = await xchangerate("USD", "INR", false); // Reads from ./v1/currencies.json (must exist) ``` -------------------------------- ### Xchange Rates CLI Examples Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/configuration.md Illustrates how to use the xchangerate CLI with and without the --local flag. The --local flag enables the use of the local cache. ```bash # Use CDN (default) xchangerate USD INR # Output: { "date": "2025-08-17", "base": "USD", "target": "INR", "rate": 87.51385 } ``` ```bash # Use local cache xchangerate USD INR --local # Output: { "date": "2025-08-17", "base": "USD", "target": "INR", "rate": 87.51385 } ``` -------------------------------- ### Example: Fetching Rates from CDN Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/configuration.md Demonstrates how to call the `xchangerate` function to fetch currency rates from the default CDN. This is the default behavior when `useCDN` is true or not provided. ```javascript const result = await xchangerate("USD", "INR"); // Fetches from https://cdn.jsdelivr.net/npm/xchange-rates@latest/v1/currencies.json ``` -------------------------------- ### Fetch USD to INR using CDN Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/cli.md Example of fetching exchange rates from the default CDN source. The command takes currency codes as arguments. ```bash $ xchangerate USD INR { "date": "2025-08-17", "base": "USD", "target": "INR", "rate": 87.51385 } ``` -------------------------------- ### Example Usage of xchangerate() Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/types.md Demonstrates how to call the xchangerate function and what the returned result object will look like. The result conforms to the ExchangeRateResult interface. ```javascript const result = await xchangerate("USD", "INR"); // result is of type ExchangeRateResult ``` -------------------------------- ### Exchange Rate Calculation Example (USD Base) Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/data-format.md Demonstrates the exchange rate calculation when the base currency is USD. ```text base = USD, target = INR USD rate = 1.0 INR rate = 87.51385 calculatedRate = 87.51385 / 1.0 = 87.51385 ``` -------------------------------- ### Example Rates Relative to USD Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/data-format.md Illustrates common currency codes and their exchange rates relative to USD. Includes examples for fiat currencies, precious metals, and cryptocurrencies. ```json { "rates": { "USD": 1.0, // Base reference rate "EUR": 0.9245, // 1 USD = 0.9245 EUR "INR": 87.51385, // 1 USD = 87.51385 INR "GBP": 0.7823, // 1 USD = 0.7823 GBP "JPY": 149.82, // 1 USD = 149.82 JPY "XAU": 0.0005, // 1 USD = 0.0005 troy oz Gold "BTC": 0.000025, // 1 USD = 0.000025 BTC "XDR": 0.766 // 1 USD = 0.766 SDR } } ``` -------------------------------- ### Using Local Cached Rates with xchangerate Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/xchangerate.md This example shows how to use locally cached exchange rates by setting the `useCDN` parameter to `false`. Ensure that the `./v1/currencies.json` file exists in your project. ```javascript const result = await xchangerate("EUR", "GBP", false); // Uses locally cached rates from ./v1/currencies.json console.log(result); // Output: // { // date: "2025-08-17", // base: "EUR", // target: "GBP", // rate: 0.8547 // } ``` -------------------------------- ### Exchange Rate Calculation Example (Non-USD Base) Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/data-format.md Demonstrates the exchange rate calculation when the base currency is not USD. ```text base = EUR, target = GBP EUR rate = 0.9245 GBP rate = 0.7823 calculatedRate = 0.7823 / 0.9245 = 0.8461 ``` -------------------------------- ### Shell Script for Exchange Rate Conversion Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/cli.md Example of integrating the `xchangerate` CLI into a bash script to fetch a rate and perform a calculation. ```bash #!/bin/bash rate=$(xchangerate USD INR | jq '.rate') amount=100 converted=$((amount * rate)) echo "$amount USD = $converted INR" ``` -------------------------------- ### Dynamic Rate Calculation Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/complete-reference.md Provides an example of how to use the exchange rate obtained from xchangerate to perform dynamic amount conversions. ```APIDOC ## convertAmount(amount, from, to) ### Description Converts a given amount from one currency to another using the exchange rate provided by `xchangerate`. ### Method `convertAmount` (custom function using `xchangerate`) ### Parameters #### Path Parameters - **amount** (number) - Required - The amount to convert. - **from** (string) - Required - The currency code to convert from. - **to** (string) - Required - The currency code to convert to. ### Request Example ```javascript async function convertAmount(amount, from, to) { const result = await xchangerate(from, to); return amount * result.rate; } const converted = await convertAmount(100, "USD", "EUR"); // If rate is 0.9245, converted = 92.45 ``` ``` -------------------------------- ### Package.json binary registration Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/modules.md Registers the 'xchangerate' command, linking it to the bin/xchangerate.js script. This allows the package to be executed as a command-line tool after installation. ```json "bin": { "xchangerate": "./bin/xchangerate.js" } ``` -------------------------------- ### Automated Versioning with semver-date.js Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/scripts-reference.md Use the `semver-date.js` script in your publish process to automatically generate a semantic version based on the current date. This example shows how to capture the version, update the npm package version, and publish. ```bash VERSION=$(node scripts/semver-date.js) npm version $VERSION npm publish ``` -------------------------------- ### Convert 100 USD to EUR using xchange-rates library Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/START-HERE.md Use the xchangerate function to get the current exchange rate and perform a conversion. Ensure the library is imported before use. ```javascript import { xchangerate } from "xchange-rates"; const result = await xchangerate("USD", "EUR"); const converted = 100 * result.rate; console.log(`$100 = €${converted}`); ``` -------------------------------- ### Example CurrencyRatesData Structure Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/types.md Illustrates the typical JSON structure for currency rates data, including the date and a nested object containing various currency codes and their corresponding exchange rates. ```json { "date": "2025-08-17", "rates": { "USD": 1.0, "EUR": 0.9245, "INR": 87.51385, "GBP": 0.7823, "JPY": 149.82, "AUD": 1.5234 } } ``` -------------------------------- ### Access Exchange Rates from Command Line Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/data-format.md Use curl to fetch the exchange rates JSON file from a CDN and jq to extract the rate for a specific currency. This example retrieves the USD rate. ```bash curl https://cdn.jsdelivr.net/npm/xchange-rates@latest/v1/currencies.json | jq '.rates.USD' ``` -------------------------------- ### Convert Multiple Currencies to USD Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md Converts amounts from various currencies to USD. This example demonstrates fetching rates for multiple currency pairs within a single execution context. ```javascript import { xchangerate } from "xchange-rates"; async function convertToUSD(amount, currency) { const result = await xchangerate(currency, "USD"); return amount * result.rate; } const rates = { "100 EUR": await convertToUSD(100, "EUR"), "100 GBP": await convertToUSD(100, "GBP"), "100 JPY": await convertToUSD(100, "JPY") }; console.log(rates); // Output: // { // "100 EUR": 108.15, // "100 GBP": 127.83, // "100 JPY": 0.67 // } ``` -------------------------------- ### Get Exchange Rate via CLI (Bash) Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/README.md Execute the xchangerate command in your terminal to fetch exchange rates. Provide the base and target currency codes as arguments. The output is a JSON object with rate details. ```bash xchangerate USD INR # { # "date": "2025-08-17", # "base": "USD", # "target": "INR", # "rate": 87.51385 # } ``` -------------------------------- ### Basic Currency Conversion Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/quick-start.md Perform a simple currency conversion from USD to INR using the xchangerate function. This example shows the basic import and function call. ```javascript import { xchangerate } from "xchange-rates"; const result = await xchangerate("USD", "INR"); console.log(result); // { // date: "2025-08-17", // base: "USD", // target: "INR", // rate: 87.51385 // } ``` -------------------------------- ### Scheduled Daily Exchange Rate Updates Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/scripts-reference.md This cron job example schedules the exchange rate update script to run daily at 2 AM. Ensure the path to the repository is correctly set. ```bash 0 2 * * * cd /path/to/repo && npm run update ``` -------------------------------- ### Fetch exchange rate in Node.js Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/README.md Import the xchangerate function and use it to get the exchange rate between two currencies. The result includes the date, base currency, target currency, and the rate. ```javascript import { xchangerate } from "xchange-rates"; (async () => { const result = await xchangerate("USD", "INR"); console.log(result); })(); ``` -------------------------------- ### Catching Fetch Errors with try-catch Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/errors.md Use a try-catch block to handle potential network or JSON parsing errors when fetching exchange rates with `useCDN: true`. This example differentiates between network and JSON errors. ```javascript try { const result = await xchangerate("USD", "INR", true); } catch (error) { if (error instanceof TypeError) { console.error("Network error:", error.message); } else if (error instanceof SyntaxError) { console.error("Invalid JSON response:", error.message); } else { console.error("Other error:", error.message); } } ``` -------------------------------- ### Bash Script with Conditional Logic based on Rate Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md An example bash script that fetches the USD to INR exchange rate, uses bc for floating-point comparison, and prints a message based on whether the rate is above a certain threshold. ```bash #!/bin/bash rate=$(xchangerate USD INR | jq '.rate') if (( $(echo "$rate > 85" | bc -l) )); then echo "INR is weak (rate: $rate)" else echo "INR is relatively strong (rate: $rate)" fi ``` -------------------------------- ### Use xchange-rates CLI for currency conversion Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/START-HERE.md The command-line interface allows for quick currency conversions without writing code. Specify the source and target currencies as arguments. ```bash xchangerate USD EUR ``` -------------------------------- ### CLI Usage with Local Cache Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md Demonstrates how to use the --local flag with the CLI to fetch exchange rates from a local cache. This can be faster for repeated lookups. ```bash $ xchangerate EUR GBP --local { "date": "2025-08-17", "base": "EUR", "target": "GBP", "rate": 0.8461 } ``` -------------------------------- ### Fetch EUR to GBP using local cache Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/cli.md Demonstrates using the `--local` flag to retrieve exchange rates from a local cache file instead of the CDN. ```bash $ xchangerate EUR GBP --local { "date": "2025-08-17", "base": "EUR", "target": "GBP", "rate": 0.8547 } ``` -------------------------------- ### Package.json main entry point Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/modules.md Defines the main entry point for the package. All .js files are treated as ES modules due to the 'type': 'module' setting. ```json "main": "index.js" ``` ```json "type": "module" ``` -------------------------------- ### Create Directory if Not Exists Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/scripts-reference.md Ensures that a specified output directory exists before writing files. Creates the directory using `fs.mkdirSync` if it's not found. ```javascript if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir); ``` -------------------------------- ### Minimal Usage Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/complete-reference.md Demonstrates the basic usage of the xchangerate function to convert one currency to another. ```APIDOC ## xchangerate(baseCurrency, targetCurrency) ### Description Fetches the exchange rate between two specified currencies. ### Method `xchangerate` ### Parameters #### Path Parameters - **baseCurrency** (string) - Required - The currency code to convert from (e.g., "USD"). - **targetCurrency** (string) - Required - The currency code to convert to (e.g., "INR"). ### Request Example ```javascript import { xchangerate } from "xchange-rates"; const result = await xchangerate("USD", "INR"); console.log(result.rate); ``` ### Response #### Success Response (200) - **date** (string) - The date for which the rates are valid. - **base** (string) - The base currency code. - **target** (string) - The target currency code. - **rate** (number) - The calculated exchange rate. #### Response Example ```json { "date": "2023-10-27", "base": "USD", "target": "INR", "rate": 87.51385 } ``` ``` -------------------------------- ### Node.js Child Process for CLI Execution Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/cli.md Demonstrates how to execute the `xchangerate` CLI from a Node.js script using `child_process.spawn` and handling its output. ```javascript import { spawn } from 'child_process'; const child = spawn('xchangerate', ['USD', 'INR']); let output = ''; child.stdout.on('data', (data) => { output += data.toString(); }); child.on('close', (code) => { if (code === 0) { const result = JSON.parse(output); console.log(`Rate: ${result.rate}`); } else { console.error('Command failed with code', code); } }); ``` -------------------------------- ### Batch Operations Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/complete-reference.md Demonstrates how to perform multiple currency conversions concurrently using `Promise.all` with the `xchangerate` function. ```APIDOC ## xchangerate(baseCurrency, targetCurrency) ### Description Fetches exchange rates for multiple currency pairs simultaneously. ### Method `xchangerate` (used within `Promise.all`) ### Parameters #### Path Parameters - **baseCurrency** (string) - Required - The currency code to convert from. - **targetCurrency** (string) - Required - The currency code to convert to. ### Request Example ```javascript const pairs = [["USD", "EUR"], ["EUR", "GBP"], ["GBP", "JPY"]]; const results = await Promise.all( pairs.map(([base, target]) => xchangerate(base, target)) ); ``` ``` -------------------------------- ### Node.js Module Usage with Async/Await Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md Demonstrates how to import and use the xchangerate function within a Node.js module using async/await syntax for fetching exchange rates and performing conversions. ```javascript // CommonJS-like usage with async/await in module import { xchangerate } from "xchange-rates"; export async function getRate(baseCurrency, targetCurrency) { return await xchangerate(baseCurrency, targetCurrency); } export async function convertAmount(amount, from, to) { const result = await xchangerate(from, to); return amount * result.rate; } ``` -------------------------------- ### xchangerate CLI Command Syntax Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/cli.md The basic command structure requires a base currency and a target currency. The `--local` flag is optional for using cached data. ```bash xchangerate [--local] ``` -------------------------------- ### Using Local Cache Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/complete-reference.md Shows how to use the xchangerate function with a local cache, bypassing CDN fetches for faster lookups. ```APIDOC ## xchangerate(baseCurrency, targetCurrency, useCDN) ### Description Fetches the exchange rate between two specified currencies, with an option to use a local cache instead of the CDN. ### Method `xchangerate` ### Parameters #### Path Parameters - **baseCurrency** (string) - Required - The currency code to convert from (e.g., "USD"). - **targetCurrency** (string) - Required - The currency code to convert to (e.g., "INR"). - **useCDN** (boolean) - Optional - If `false`, uses the local cache. Defaults to `true`. ### Request Example ```javascript // Requires: npm run update (must be run once first) const result = await xchangerate("USD", "INR", false); ``` ### Response #### Success Response (200) - **date** (string) - The date for which the rates are valid. - **base** (string) - The base currency code. - **target** (string) - The target currency code. - **rate** (number) - The calculated exchange rate. #### Response Example ```json { "date": "2023-10-27", "base": "USD", "target": "INR", "rate": 87.51385 } ``` ``` -------------------------------- ### Get Exchange Rate Function Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/START-HERE.md Use this asynchronous function to retrieve exchange rates between two currencies. It defaults to using a CDN for rate updates but can be configured to use a local cache. ```javascript async function xchangerate(baseCurrency, targetCurrency, useCDN = true) // Returns: { date, base, target, rate } ``` -------------------------------- ### Piping CLI Output to Variables with jq Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md Demonstrates how to capture the JSON output of the xchangerate CLI command into a bash variable and then use jq to parse the variable and extract individual components like base currency, target currency, and rate. ```bash # Store result in variable result=$(xchangerate USD EUR) base=$(echo $result | jq -r '.base') target=$(echo $result | jq -r '.target') rate=$(echo $result | jq '.rate') echo "1 $base = $rate $target" ``` -------------------------------- ### CLI Runtime Error Handling Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/errors.md The CLI catches errors from the `xchange-rates()` function, prints an error message to stderr, and exits with code 1. This example shows an error for an invalid target currency. ```bash $xchangerate USD INVALID Error: Target currency INVALID not found $ echo $? ``` ```bash 1 ``` -------------------------------- ### Library Call with Default Parameters Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/configuration.md Use this to fetch exchange rates using default CDN data source. No additional configuration is needed. ```javascript xchangerate("USD", "INR") ``` -------------------------------- ### CLI Conversion Using Local Cache Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/quick-start.md Execute a command-line currency conversion while utilizing the local cache. This is useful for offline access or faster retrieval. ```bash xchangerate USD INR --local ``` -------------------------------- ### Calculate Exchange Rate (JavaScript) Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/README.md Use the xchangerate function to get the exchange rate between two currencies. The function returns an object containing the date, base currency, target currency, and the calculated rate. ```javascript import { xchangerate } from "xchange-rates"; const result = await xchangerate("USD", "INR"); // { date: "2025-08-17", base: "USD", target: "INR", rate: 87.51385 } const amount = 100; const converted = amount * result.rate; // 8751.39 ``` -------------------------------- ### Load Environment Variables and Construct API URL Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/scripts-reference.md Loads environment variables using `dotenv` and constructs the API URL by combining base URL and API key. Ensure `.env` file is present with `XCR_KEY1` and `XCR_URL1`. ```javascript import dotenv from 'dotenv'; dotenv.config(); const KEY = process.env.XCR_KEY1; const URL = process.env.XCR_URL1; const API_URL = `${URL}${KEY}`; ``` -------------------------------- ### Convert Currency from USD to INR Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/index.md Demonstrates how to convert a currency from USD to INR using the xchangerate function. Ensure the library is imported. ```javascript import { xchangerate } from "xchange-rates"; const result = await xchangerate("USD", "INR"); const amount = 100; const converted = amount * result.rate; console.log(`$${amount} USD = ₹${converted} INR`); ``` -------------------------------- ### Update Script Dependencies and Execution Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/modules.md Illustrates the dependencies and execution method for the 'updateRates.js' script, which fetches and caches exchange rates. ```javascript #!/usr/bin/env node import fs from 'fs'; import path from 'path'; import fetch from 'node-fetch'; import dotenv from 'dotenv'; import { format } from 'date-fns'; dotenv.config(); const { XCR_KEY1, XCR_URL1 } = process.env; const ratesPath = path.resolve(__dirname, '../v1/currencies.json'); async function updateRates() { try { const response = await fetch(`${XCR_URL1}?apikey=${XCR_KEY1}`); if (!response.ok) { throw new Error(`API request failed with status ${response.status}`); } let data = await response.json(); // Clean response data delete data.disclaimer; delete data.license; data.date = format(new Date(), 'yyyy.MM.dd'); // Ensure v1 directory exists await fs.promises.mkdir(path.dirname(ratesPath), { recursive: true }); // Write to local cache await fs.promises.writeFile(ratesPath, JSON.stringify(data, null, 2)); console.log('Exchange rates updated successfully!'); } catch (error) { console.error('Error updating exchange rates:', error); process.exit(1); } } updateRates(); ``` -------------------------------- ### Set up offline mode for xchange-rates Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/START-HERE.md Run the 'npm run update' command to download and cache exchange rate data for offline use. This command is typically run only once. ```bash npm run update # First time only ``` -------------------------------- ### Running the Update Script Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/configuration.md Provides commands to run the `updateRates.js` script, either via an npm script or directly using Node.js. This script fetches, processes, and saves currency rate data. ```bash npm run update # Or directly: node scripts/updateRates.js ``` -------------------------------- ### Basic CDN Usage of xchangerate Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/xchangerate.md Use this snippet to fetch real-time exchange rates from the CDN. The base and target currencies are automatically converted to uppercase. The output includes the date of the rates, base and target currencies, and the calculated rate. ```javascript import { xchangerate } from "xchange-rates"; const result = await xchangerate("USD", "INR"); console.log(result); // Output: // { // date: "2025-08-17", // base: "USD", // target: "INR", // rate: 87.51385 // } ``` -------------------------------- ### CLI Command Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/README.md Command-line interface for fetching exchange rates. It takes base and target currencies as arguments and supports a local flag. ```APIDOC ## CLI Command: xchangerate ### Description Allows users to fetch exchange rates directly from the command line. ### Usage ```bash xchangerate [--local] ``` ### Arguments - **baseCurrency** (string) - Required - The currency code from which to convert. - **targetCurrency** (string) - Required - The currency code to which to convert. ### Options - **--local** (flag) - Optional - Use the local cache instead of the CDN. ``` -------------------------------- ### Full Import Statement Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/modules.md Shows how to import the 'xchangerate' function from the 'xchange-rates' package in an ES module. ```javascript import { xchangerate } from "xchange-rates"; ``` -------------------------------- ### Basic CLI Currency Conversion Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/quick-start.md Perform a currency conversion directly from the command line. This command fetches the exchange rate between USD and INR. ```bash xchangerate USD INR ``` -------------------------------- ### CLI Command Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/index.md Command-line interface for fetching exchange rates. Accepts base and target currencies as arguments and outputs the result in JSON format. ```APIDOC ## CLI Command ### Description Provides a command-line interface to fetch exchange rates directly from the terminal. ### Usage ```bash xchangerate [--local] ``` ### Parameters - **baseCurrency** (string) - Required - The currency code from which to convert. - **targetCurrency** (string) - Required - The currency code to which to convert. - **--local** (flag) - Optional - Use this flag to fetch rates from the local cache instead of the CDN. ### Output - JSON object (pretty-printed) containing the exchange rate details. ### Exit Codes - `0` - Success. - `1` - Error. ``` -------------------------------- ### Extracting Rate with jq from CLI Output Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md Shows how to pipe the JSON output of the xchangerate CLI command to jq to extract specific fields, in this case, the exchange rate. ```bash $ xchangerate USD INR | jq '.rate' 87.51385 ``` -------------------------------- ### Update Exchange Rates Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/index.md Run this command to fetch and cache the latest exchange rates. It requires an .env file with specific API keys and URLs. ```bash npm run update # Requires: .env file with XCR_KEY1 and XCR_URL1 ``` -------------------------------- ### Use Local Cache in Code Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/quick-start.md Call the xchangerate function with the `useCDN` parameter set to `false` to explicitly use the local cache. ```javascript const result = await xchangerate("USD", "INR", false); ``` -------------------------------- ### Simple Currency Converter Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md Converts a given amount from one currency to another using the fetched exchange rate. Ensure the 'xchange-rates' library is imported. ```javascript import { xchangerate } from "xchange-rates"; async function convertCurrency(amount, from, to) { const result = await xchangerate(from, to); return amount * result.rate; } const usd100ToInr = await convertCurrency(100, "USD", "INR"); console.log(`100 USD = ${usd100ToInr.toFixed(2)} INR`); // Output: 100 USD = 8751.39 INR ``` -------------------------------- ### Dynamic Rate Calculation with xchangerate Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/complete-reference.md Create a helper function to dynamically convert amounts using xchangerate. This function fetches the rate and multiplies it by the given amount. ```javascript async function convertAmount(amount, from, to) { const result = await xchangerate(from, to); return amount * result.rate; } const converted = await convertAmount(100, "USD", "EUR"); // If rate is 0.9245, converted = 92.45 ``` -------------------------------- ### Converting Multiple Currency Pairs with xchangerate Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/xchangerate.md This snippet demonstrates how to iterate over an array of currency pairs and use the xchangerate function to convert each pair. It logs the exchange rate for each conversion. ```javascript const pairs = [ ["USD", "INR"], ["EUR", "GBP"], ["JPY", "AUD"] ]; for (const [base, target] of pairs) { const result = await xchangerate(base, target); console.log(`${base} to ${target}: ${result.rate}`); } ``` -------------------------------- ### Generate Version String with semver-date.js Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/scripts-reference.md Run this script to generate a version string based on the current date. Repeated executions on the same day will produce incrementally versioned strings (e.g., `2025.8.17-1`). ```bash $ node scripts/semver-date.js 2025.8.17 $ node scripts/semver-date.js 2025.8.17-1 $ node scripts/semver-date.js 2025.8.17-2 ``` -------------------------------- ### Scheduled Cache Updates via Cron Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/quick-start.md Set up a cron job to automatically update the local exchange rate cache daily. This ensures up-to-date rates for offline use. ```bash # Update rates daily via cron 0 2 * * * cd /path/to/project && npm run update ``` -------------------------------- ### Node.js Cron Job for Logging Exchange Rates Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md Schedule a recurring task to fetch and log exchange rates to a file. Requires 'cron' and 'xchange-rates' packages. ```javascript import { CronJob } from 'cron'; import { xchangerate } from 'xchange-rates'; import fs from 'fs'; const job = new CronJob('0 * * * *', async () => { try { const result = await xchangerate('USD', 'EUR'); fs.appendFileSync('rates.log', `${new Date().toISOString()}: 1 USD = ${result.rate} EUR\n`); console.log('Rate logged:', result.rate); } catch (error) { console.error('Error fetching rate:', error.message); } }); job.start(); ``` -------------------------------- ### Bash Script for Looping Through Conversions Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md This bash script iterates through a predefined associative array of currency conversions, fetching and displaying the exchange rate for each pair using xchangerate and jq. ```bash #!/bin/bash declare -A conversions=( ["USD"]="EUR" ["EUR"]="GBP" ["GBP"]="JPY" ) for from in "${!conversions[@]}"; do to="${conversions[$from]}" xchangerate $from $to | jq '{from: .base, to: .target, rate: .rate}' done ``` -------------------------------- ### Batch Operations with xchangerate Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/complete-reference.md Perform multiple currency conversions concurrently using `Promise.all` and `map`. This is efficient for processing a list of currency pairs. ```javascript const pairs = [["USD", "EUR"], ["EUR", "GBP"], ["GBP", "JPY"]]; const results = await Promise.all( pairs.map(([base, target]) => xchangerate(base, target)) ); ``` -------------------------------- ### Bash Script for Currency Conversion Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md A bash script that takes an amount and two currency codes as arguments, fetches the exchange rate using xchangerate and jq, and then calculates and displays the converted amount. ```bash #!/bin/bash amount=$1 from=$2 to=$3 rate=$(xchangerate $from $to | jq '.rate') result=$(echo "$amount * $rate" | bc) echo "$amount $from = $result $to" ``` -------------------------------- ### Query npm Registry Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/scripts-reference.md Fetches package data from the npm registry to check for existing versions. It retrieves both published versions and all version times to ensure a comprehensive check. ```javascript const res = await fetch('https://registry.npmjs.org/xchange-rates'); const data = await res.json(); ``` -------------------------------- ### xchangerate Using Local Cache Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/complete-reference.md Call xchangerate with the third argument set to false to use the local cache. Ensure you have run `npm run update` first. ```javascript // Requires: npm run update (must be run once first) const result = await xchangerate("USD", "INR", false); ``` -------------------------------- ### Error Handling with xchangerate Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/xchangerate.md Illustrates how to handle potential errors when using the xchangerate function, such as when a target currency is not found. The catch block will log the error message. ```javascript try { const result = await xchangerate("USD", "INVALID"); } catch (error) { console.error(error.message); // Output: "Target currency INVALID not found" } ``` -------------------------------- ### Local Cache Configuration Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/quick-start.md Configure environment variables for the local cache. This includes setting the API key and the base URL for fetching rates. ```env XCR_KEY1=your_api_key XCR_URL1=https://api.example.com/latest?access_key= ``` -------------------------------- ### Update Local Cache Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/quick-start.md Run a script to update the local cache with the latest exchange rates. This is necessary for offline usage. ```bash npm run update ``` -------------------------------- ### xchangerate Function Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/modules.md The main `xchangerate` function is the primary export of the library, used for fetching exchange rates. It can optionally use a CDN for fetching rates. ```APIDOC ## xchangerate(baseCurrency, targetCurrency, useCDN = true) ### Description Fetches the exchange rate between a base currency and a target currency. It can utilize a Content Delivery Network (CDN) for fetching the latest rates, or use locally cached data if `useCDN` is set to `false`. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Async Function ### Endpoint N/A (SDK Function) ### Request Example ```javascript import { xchangerate } from "xchange-rates"; async function getRate() { const rate = await xchangerate('USD', 'EUR', true); console.log(rate); } getRate(); ``` ### Response #### Success Response (200) - **rate** (number) - The calculated exchange rate. - **base** (string) - The base currency code. - **target** (string) - The target currency code. - **timestamp** (string) - The date and time the rate was fetched or calculated. #### Response Example ```json { "rate": 0.92, "base": "USD", "target": "EUR", "timestamp": "2023-10-27T10:00:00.000Z" } ``` ``` -------------------------------- ### Success Output JSON Format Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/cli.md When successful, the CLI outputs a JSON object containing the exchange rate details. This format is achieved using `JSON.stringify(result, null, 2)` for 2-space indentation. ```json { "date": "2025-08-17", "base": "USD", "target": "INR", "rate": 87.51385 } ``` -------------------------------- ### Manually Update Exchange Rates Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/scripts-reference.md Execute this command to manually update the exchange rates. The output confirms a successful update and shows the modified `currencies.json` file. ```bash $ npm run update Exchange rates updated successfully! $ ls -la v1/ total 12 -rw-r--r-- 1 user group 2048 Aug 17 14:23 currencies.json ``` -------------------------------- ### xchangerate Function Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/api-reference/xchangerate.md The primary async function for retrieving real-time currency exchange rates. It fetches data from a CDN or local JSON file and calculates the conversion rate between a base and target currency. ```APIDOC ## xchangerate(baseCurrency, targetCurrency, useCDN = true) ### Description Retrieves real-time currency exchange rates and calculates the conversion rate between two specified currencies. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **baseCurrency** (string) - Required - ISO 4217 currency code (case-insensitive). Examples: `"USD"`, `"EUR"`, `"INR"`. - **targetCurrency** (string) - Required - ISO 4217 currency code (case-insensitive). Examples: `"INR"`, `"GBP"`, `"JPY"`. - **useCDN** (boolean) - Optional - Default: `true`. If `true`, fetches rates from a CDN. If `false`, uses local cached rates. ### Return Type Returns a Promise that resolves to an object containing the exchange rate details. ### Response #### Success Response (200) - **date** (string) - ISO 8601 date (YYYY-MM-DD format) when rates were last updated. - **base** (string) - The base currency code (uppercase). - **target** (string) - The target currency code (uppercase). - **rate** (number) - The calculated exchange rate (targetCurrency units per baseCurrency unit). ### Throws - **Error**: When `useCDN` is `false` and no local JSON file exists at `./v1/currencies.json`. - **Error**: When `baseCurrency` is not found in the rates data. - **Error**: When `targetCurrency` is not found in the rates data. ### Examples #### Basic CDN Usage (Default) ```javascript import { xchangerate } from "xchange-rates"; const result = await xchangerate("USD", "INR"); console.log(result); // Output: // { // date: "2025-08-17", // base: "USD", // target: "INR", // rate: 87.51385 // } ``` #### Using Local Cached Rates ```javascript const result = await xchangerate("EUR", "GBP", false); console.log(result); // Output: // { // date: "2025-08-17", // base: "EUR", // target: "GBP", // rate: 0.8547 // } ``` #### Error Handling ```javascript try { const result = await xchangerate("USD", "INVALID"); } catch (error) { console.error(error.message); // Output: "Target currency INVALID not found" } ``` ``` -------------------------------- ### Error Handling for Invalid Currencies Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md Demonstrates how to catch and handle errors when providing invalid base or target currency codes, or if the local cache is not found. ```javascript import { xchangerate } from "xchange-rates"; try { const result = await xchangerate("USD", "INVALID"); } catch (error) { if (error.message.includes("Target currency")) { console.error("Invalid target currency"); } else if (error.message.includes("Base currency")) { console.error("Invalid base currency"); } else if (error.message === "Local JSON not available") { console.error("Local cache not found. Run: npm run update"); } else { console.error("Unexpected error:", error.message); } } ``` -------------------------------- ### Express.js API for Currency Conversion Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/examples.md Set up an Express.js server to handle currency conversion requests. Requires 'express' and 'xchange-rates' packages. ```javascript import express from 'express'; import { xchangerate } from 'xchange-rates'; const app = express(); app.get('/convert', async (req, res) => { const { amount, from, to } = req.query; if (!amount || !from || !to) { return res.status(400).json({ error: 'Missing parameters' }); } try { const result = await xchangerate(from, to); const converted = parseFloat(amount) * result.rate; res.json({ amount: parseFloat(amount), from: result.base, to: result.target, rate: result.rate, converted: converted, date: result.date }); } catch (error) { res.status(400).json({ error: error.message }); } }); app.listen(3000, () => console.log('Server running on port 3000')); ``` ```bash curl "http://localhost:3000/convert?amount=100&from=USD&to=INR" ``` -------------------------------- ### CLI Usage Message for Insufficient Arguments Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/errors.md The CLI tool displays a usage message and exits with code 1 when fewer than two arguments are provided. This is the expected output format. ```bash Usage: xchangerate [--local] ``` -------------------------------- ### Package.json scripts Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/modules.md Defines custom scripts for the package. The 'update' script is used to refresh currency rates, while 'test' is a placeholder. ```json "scripts": { "update": "node scripts/updateRates.js", "test": "echo \"Error: no test specified\" && exit 1" } ``` -------------------------------- ### Async/Await Usage in CLI Source: https://github.com/jayadevpanthaplavil/xchange-rates/blob/main/_autodocs/cli.md The main CLI logic uses async/await for handling asynchronous operations, with `.then()` for success and `.catch()` for errors. ```javascript xchangerate(baseCurrency, targetCurrency, useCDN) .then(result => { console.log(JSON.stringify(result, null, 2)); }) .catch(err => { console.error('Error:', err.message); process.exit(1); }); ```