Reputation: 9
I want to work with the data from a csv file and I have used csv-parser to do that.
const csv = require('csv-parser')
const fs = require('fs')
const results: any[] = [];
var value = fs.createReadStream('file.csv')
.pipe(csv())
.on('data', (data: any) => results.push(data))
.on('end', () => {
console.log(results);
return results;
});
The parser works well and I get the csv printed, but I want to return the data in the value variable.
What should I do?
Upvotes: 0
Views: 2004
Reputation: 21
Wrap the stream process with Promise
.
const parse = (filePath) => {
const results = [];
return new Promise((resolve, reject) => {
fs.createReadStream(filePath)
.pipe(csv())
.on('data', (data) => results.push(data))
.on('error', reject)
.on('end', () => resolve(results));
});
};
Then get the value with await
:
(async () => {
const value = await parse('data.csv');
console.log(value);
})();
Upvotes: 0
Reputation: 368
In your snippet the CSV file read in is pushed to the array results
already. So you can use that, or if you really prefer to use an array entitled value
, see the snippet below.
const csv = require('csv-parser')
const fs = require('fs')
const value = [];
fs.createReadStream('data.csv')
.pipe(csv())
.on('data', (data) => value.push(data))
.on('end', () => {
console.log(value);
});
Upvotes: 2