I am trying to parse a csv file with typescript which I am totally new to. I cannot get the parser working with the correct typings.
Without typings everything is easy:
var fs = require('fs');
var parse = require('csv-parse');
var parser = parse({delimiter: ';'}, function(err, data){
console.log(data);
});
fs.createReadStream(__dirname+'/fs_read.csv').pipe(parser);
But when it comes to typescript I get errors, I installed the typings from dt :
import * as csvParse from 'csv-parse';
import fs = require('fs');
var myParser:csvParse.CsvParser = csvParse({delimiter: ','}, function(data, err) {
console.log(data);
});
I get the error
Type 'void | CsvParser' is not assignable to type 'CsvParser'.
Can anyone give me a hint or used csv-parse with typescript before and share their code?
The Comma Separated Values (CSV) Parser reads and writes data in a CSV format. Note: In the Config Editor, the parameters are set in the Parser tab of the Connector.
You will use the fs module's createReadStream() method to read the data from the CSV file and create a readable stream. You will then pipe the stream to another stream initialized with the csv-parse module to parse the chunks of data. Once the chunks of data have been parsed, you can log them in the console.
Do not explain which type you want as a result of method csvParse
:
var myParser = csvParse({delimiter: ','}, function(data, err) {
console.log(data);
});
<>
var myParser:csvParse.CsvParser = <csvParse.CsvParser> csvParse({delimiter: ','}, function(data, err) {
console.log(data);
});
Note: This only work with
.ts
files. In.jsx
files you will see error "Expected corresponding JSX closing tag for ..."
as
var myParser:csvParse.CsvParser = csvParse({delimiter: ','}, function(data, err) {
console.log(data);
}) as csvParse.CsvParser;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With