Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript csv-parse

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?

like image 759
niklas Avatar asked Sep 14 '16 10:09

niklas


People also ask

What is Csvparser?

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.

How do I parse a csv file in node?

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.


1 Answers

1. Let typescript do the work for you

Do not explain which type you want as a result of method csvParse:

var myParser = csvParse({delimiter: ','}, function(data, err) {
  console.log(data);
});

2. Use the original cast operator <>

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 ..."

3. Use the new operator as

var myParser:csvParse.CsvParser = csvParse({delimiter: ','}, function(data, err) {
  console.log(data);
}) as csvParse.CsvParser;
like image 119
Pavel Petrovich Avatar answered Sep 27 '22 19:09

Pavel Petrovich