I am simply trying to fetch data from a CSV file where I have to loop over an array of objects. But the loop is not happening and its throwing that array.map or array.forEach is not a function. The HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
</head>
<body>
<canvas id="chart" width="400" height="400">
</canvas>
<script>
fetchData();
async function fetchData(){
try {
const data = await fetch('http://localhost:3000/');
const table = await data.text();
console.log(table);
table.map(item => {
console.log(item["Year"])
});
} catch (error) {
console.error(error);
}
}
</script>
</body>
</html>
The backend node.js file:
const express = require('express');
var app = express();
const cors = require('cors')
var fs = require('fs').promises;
var parse = require('csv-parse/lib/sync');
app.get('/',cors(), async (req, res) => {
(async function () {
const fileContent = await fs.readFile('test.csv');
const records = parse(fileContent,{columns:true});
res.send(records);
})();
});
app.listen('3000',() => console.log('listening on 3000'));
The fetched data looks like this: [{"Year":"1880","Glob":"-.16","NHem":"-.27","SHem":"-.04","24N-90N":"-.35","24S-24N":"-.13","90S-24S":"-.01","64N-90N":"-.81","44N-64N":"-.46","24N-44N":"-.26","EQU-24N":"-.15","24S-EQU":"-.10","44S-24S":"-.03","64S-44S":".05","90S-64S":".65"},{"Year":"1881","Glob":"-.08","NHem":"-.17","SHem":".01","24N-90N":"-.33","24S-24N":".10","90S-24S":"-.06","64N-90N":"-.92","44N-64N":"-.43","24N-44N":"-.18","EQU-24N":".10","24S-EQU":".11","44S-24S":"-.05","64S-44S":"-.07","90S-64S":".58"},{"Year":"1882","Glob":"-.10","NHem":"-.20","SHem":"-.01","24N-90N":"-.29","24S-24N":"-.05","90S-24S":".02","64N-90N":"-1.42","44N-64N":"-.25","24N-44N":"-.12","EQU-24N":"-.05","24S-EQU":"-.05","44S-24S":".02","64S-44S":".04","90S-64S":".61"},.....(more objects)]
Can you try JSON.parse(table).map(...
. From the error it looks like table is not of type array.