1

Can anyone tell me the basic syntax of how to read and write text file i.e file handling in typescript. And also if anyone can give me corresponding link I'll be grateful.

Zeeshan Malik
  • 627
  • 1
  • 14
  • 31
  • TypeScript is not a language or a library; it's a type layer on top of JavaScript. It provides nothing having anything to do with file handling. Angular is a framework built in TS/JS, and also provides no special file handling capabilities of its own. If your idea is to read and write a local text file, you can't do that in any web application built in any framework in any language. –  Jun 20 '17 at 06:14
  • As I said, no, if you mean a local file on the machine running the browser running the app. If you want to read and write a text file on the server, there are lots of ways, which are well documented. –  Jun 20 '17 at 06:25
  • you will have to do it on server.. make api call with whatever data you want to write... understand basics of client vs server plz – harishr Jun 20 '17 at 06:31
  • I'm not sure how many times you want me to say **NO**. If you want more hints, you need to carefully describe the exact problem you are trying to solve. Are you trying to read and write a local file from within the app while it is running? You can't do that. Do you want to include the contents of a text file somehow into your app at build time? There are of course ways to do that. –  Jun 20 '17 at 06:33
  • Ok, can you give any example how to read/write text file on server – Zeeshan Malik Jun 20 '17 at 06:37
  • Now you got me. I want to load contents of a text file in my app. I just want to know the basic syntax. – Zeeshan Malik Jun 20 '17 at 06:43
  • like: reader = new Reader(); Using this type of stuff. – Zeeshan Malik Jun 20 '17 at 06:45

1 Answers1

0

Have a method readTextFile in your class. This is totally based on Javascript

readTextFile(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                console.log(allText); // Here is the contents of the file
            }
        }
    }
    rawFile.send(null);
}

And then call the function with it's path

this.readTextFile(path_of_the_file_to_be_read_as_string);

in the above line, this is based on the place fro where you are calling the function.

We are able to read files with javascript but we can't write into files. https://stackoverflow.com/a/21012689/6554634

Mr_Perfect
  • 8,254
  • 11
  • 35
  • 62