After receiving a CSV file from a URL, I am converting each row into an array of objects.
const translation = {
'緯度': 'latitude',
'経度': 'longitude',
'測定局コード': 'Measuring station code',
'測定局名称': 'Bureau name',
'所在地': 'location',
'測定局種別': 'Measuring station type',
'問い合わせ先': 'Contact information',
'都道府県コード': 'Prefecture code'
}
const csv_url = 'https://soramame.env.go.jp/data/map/kyokuNoudo/2022/10/06/01.csv';
// requesting the CSV file from csv_url and creating an array of station objects
var stations = [];
request(csv_url, (err, res, body) => {
if (err || res.statusCode !== 200) {
console.log(err);
}
else {
const rows = body.split('\n');
const headers = rows[0].split(',');
for (let i = 1; i < rows.length; i++) { // starting at 1 to skip headers
let station = {}; // creating a new station object for each row
const row = rows[i].split(','); // splitting the row into columns
for (let j = 0; j < row.length; j++) { // iterating through each column
station[translation[headers[j]]] = row[j]; // adding the value to the station object using the header as the key
}
var data = stations.push(station)
console.log(stations)
return data;
}
}
}
);
Everything works fine... when I console.log(stations)
inside the function, the expected output is displayed.
{
latitude: '43.123333',
longitude: '141.245000',
'Measuring station code': '01107030',
'Bureau name': '手稲',
location: '札幌市手稲区前田2-12',
'Measuring station type': '一般局',
'Contact information': '札幌市',
'Prefecture code': '01'
}
{
latitude: '43.123333',
longitude: '141.245000',
'Measuring station code': '01107030',
'Bureau name': '手稲',
location: '札幌市手稲区前田2-12',
'Measuring station type': '一般局',
'Contact information': '札幌市',
'Prefecture code': '01'
}
{
latitude: '43.123333',
longitude: '141.245000',
'Measuring station code': '01107030',
'Bureau name': '手稲',
location: '札幌市手稲区前田2-12',
'Measuring station type': '一般局',
'Contact information': '札幌市',
'Prefecture code': '01'
}
However, when I console.log(stations)
outside of the function, an empty list is returned. I have declared 'stations' outside of the function, and the function is supposed to append the objects to the array. Why isn't it working as expected and how can this be resolved? Additionally, returning 'data' does not return the array from 'stations' either.