Skip to content

Instantly share code, notes, and snippets.

@RobinKnipe
Last active May 8, 2023 22:33
Show Gist options
  • Select an option

  • Save RobinKnipe/11b2d3675c36fb4896feadd20deaf119 to your computer and use it in GitHub Desktop.

Select an option

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.
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);
@RobinKnipe
Copy link
Author

Just npm i csv-parser, then run node gbp2eur.js in.csv out.csv.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment