pitosalas
pitosalas

Reputation: 10862

Read a csv file in Typescript

I'm getting into TypeScript as a way to write simple utility programs, meant to be run on the command line. There are a bunch of basic questions I have, maybe someone can give me pointers.

  1. I am assuming that I will run the app by a command like: $ node myapp.js
  2. If I want to run it by $ myapp.js I need a shebang line in the js, but I can't see how to have that flow from the .ts file, so I have to post edit the js file, right?
  3. How do I just open a text file from a local path within TypeScript? Where do I look for the right incantation?
  4. And once I have the text file open I have to process it as a cvs. I found a library called node-cvs but I am not sure how to connect the dots.

Upvotes: 2

Views: 12026

Answers (2)

Sam Saint-Pettersen
Sam Saint-Pettersen

Reputation: 511

You would need to do something like:

/// <reference path="node.d.ts" />
/// <reference path="a-type-definition-for-node-csv.d.ts" />

import fs = require('fs');
import parse = require('node-csv');

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

fs.createReadStream(__dirname+'/fs_read.csv').pipe(parser);

Upvotes: 2

basarat
basarat

Reputation: 275819

  1. I am assuming that I will run the app by a command like: $ node myapp.js

Yes. TypeScript compiles to JavaScript.

  1. If I want to run it by $ myapp.js I need a shebang line in the js, but I can't see how to have that flow from the .ts file, so I have to post edit the js file, right?

No. Take a look at my workaround : https://github.com/npm/npm/issues/6674#issuecomment-108132800

  1. How do I just open a text file from a local path within typescript? Where do I look for the right incantation?

fs.readFile in node. You can use it in typescript (and even provide type safety using node.d.ts : https://github.com/borisyankov/DefinitelyTyped/blob/master/node/node.d.ts

  1. And once I have the text file open I have to process it as a cvs. I found a library called node-cvs but I am not sure how to connect the dots.

You can just do require('node-cvs') same as javascript

Upvotes: 6

Related Questions