currency-utils-converter

1.0.3 • Public • Published

Currency Utils

currency-utils-converter is a simple Node.js module for retrieving real-time currency exchange rates and converting values between currencies. The module uses a free exchange rate API and provides an easy-to-use interface for currency operations.

Installation

Install the module in your project using npm:

npm install currency-utils

Usage

The module allows you to convert between currencies and format amounts in a specific currency.

Example

const CurrencyUtils = require('currency-utils');

// Use the default API URL or specify a custom one
const API_URL = 'https://api.exchangerate-api.com/v4/latest/USD';
const currencyUtils = new CurrencyUtils(API_URL);

(async () => {
  try {
    // Convert 100 USD to EUR
    const convertedAmount = await currencyUtils.convert(100, 'USD', 'EUR');
    console.log(`100 USD in EUR: ${convertedAmount}`);

    // Format the converted amount
    const formattedAmount = currencyUtils.format(convertedAmount, 'EUR', 'en-US');
    console.log(`Formatted: ${formattedAmount}`);
  } catch (error) {
    console.error(`Error: ${error.message}`);
  }
})();

Methods

convert(amount, fromCurrency, toCurrency)

Converts an amount from one currency to another.

  • amount (number): The amount to convert.
  • fromCurrency (string): The currency to convert from (e.g., 'USD', 'EUR').
  • toCurrency (string): The currency to convert to (e.g., 'EUR', 'JPY').

Returns a promise with the converted amount.

format(amount, currency, locale)

Formats an amount in a specific currency.

  • amount (number): The amount to format.
  • currency (string): The currency to use for formatting (e.g., 'USD', 'EUR').
  • locale (string): The locale to use for formatting (e.g., 'en-US', 'de-DE').

Returns the formatted string.


API

By default, the module uses the ExchangeRate-API to fetch exchange rates.

Default API URL: https://api.exchangerate-api.com/v4/latest/USD

You can customize the API URL by passing it to the CurrencyUtils constructor:

const customApiUrl = 'https://example.com/api/latest/USD';
const currencyUtils = new CurrencyUtils(customApiUrl);

The API must return data in the following format:

{
  "rates": {
    "EUR": 0.85,
    "JPY": 110.53
  },
  "base": "USD"
}

Error Handling

If the API is inaccessible or returns invalid data, the module will throw an error with detailed information to help you troubleshoot.

Example error message:

Error fetching data from API: Invalid URL or data format.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Package Sidebar

Install

npm i currency-utils-converter

Weekly Downloads

96

Version

1.0.3

License

MIT

Unpacked Size

6.17 kB

Total Files

4

Last publish

Collaborators

  • abz120