I'm very noob at Javascript. All I'm trying to do is read a CSV file from local and playaround with the data, like converting the rows into arrays of array. I came across the fs.createReadStream, which helps to read csv data but I'm unable to utilize the processed csv data later. I read in some thread, and I guess the issue with the synchronisation.
My code looks like this-
ar abc = []
const csv = require('csv-parser');
const fs = require('fs');
fs.createReadStream('data.csv')
.pipe(csv())
.on('data', (row) => {
var nums =[];
// console.log(row);
nums.push(row['time'])
nums.push(row['return'])
abc.push(nums)
})
.on('end', function () {
console.log(abc)
})
var final_sort= []
console.log()
for (let i = 0; i < abc.length; i=i+5){
final_sort.push(abc[i])
}
console.log(final_sort)
this outputs log outside fs first then outputs the fs.createReadStream. I wanted the fs. createReadStream to be processed first, then I can utilize the data further.
if you want to handle your sequence then you have to try promises
if your task is read all data and then sort then your code will be like
var abc = []
const csv = require('csv-parser');
const fs = require('fs');
// -----------1 process start
await new Promise((resolve, reject) => {
fs.createReadStream('data.csv')
.pipe(csv())
.on('data', (row) => {
var nums = [];
// console.log(row);
nums.push(row['time'])
nums.push(row['return'])
abc.push(nums)
})
.on('end', function () {
console.log(abc)
//---------- 2 return after all data read
resolve()
})
});
//---------- 3 here you get all data
var final_sort = []
console.log()
for (let i = 0; i < abc.length; i = i + 5) {
final_sort.push(abc[i])
}
console.log(final_sort)
for more refenerce understanding-javascript-promises