Last active
May 8, 2023 22:33
-
-
Save RobinKnipe/11b2d3675c36fb4896feadd20deaf119 to your computer and use it in GitHub Desktop.
Take a CSV file of date and GBP, and add the GBP=>EUR rate and converted EUR amount.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const { createReadStream, createWriteStream } = require('fs'); | |
| const { pipeline } = require('stream'); | |
| const csv = require('csv-parser'); | |
| const exchangeRatesUrl = 'https://api.exchangerate.host'; | |
| async function getExchangeRate(date) { | |
| const response = await fetch(`${exchangeRatesUrl}/convert?from=GBP&to=EUR&date=${date}`); | |
| const { result } = await response.json(); | |
| return result; | |
| } | |
| async function* addEurValue(transformStream) { | |
| for await (const row of transformStream) { | |
| const date = row.date; | |
| const gbp = parseFloat(row.GBP.replace(',', '.')); | |
| const exchangeRate = await getExchangeRate(date); | |
| row.rate = exchangeRate; | |
| row.EUR = (gbp * exchangeRate).toFixed(2); | |
| yield row; | |
| } | |
| } | |
| async function* csvStringify(transformStream) { | |
| yield 'date,GBP,rate,EUR\n'; | |
| for await (const object of transformStream) | |
| yield `${object.date},${object.GBP},${object.rate},${object.EUR}\n`; | |
| } | |
| async function transform(inputFile, outputFile) { | |
| pipeline( | |
| createReadStream(inputFile), | |
| csv(), | |
| addEurValue, | |
| csvStringify, | |
| createWriteStream(outputFile), | |
| (err) => { | |
| if (err) { | |
| console.error('Error:', err); | |
| } else { | |
| console.log('Transformation complete'); | |
| } | |
| } | |
| ); | |
| } | |
| const [, , inputFile, outputFile] = process.argv; | |
| transform(inputFile, outputFile); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just
npm i csv-parser, then runnode gbp2eur.js in.csv out.csv.