2

I am working with Angular 5, I have an application in which I need to read an AMP HTML file as text. This file is contained in a component and should only be accessed from this component.

I would like to be able to open the file in read-only by giving its name.

I'm actually searching for something like this:

let file = open('amp.html');

Is it possible? If not how can I do to achieve this?

Raphael
  • 563
  • 1
  • 10
  • 22
  • 3
    In what environment? From a browser? NodeJS? Windows Metro app? Something else? – T.J. Crowder Dec 30 '17 at 10:24
  • From the browser, you can't access the file system with JS due to the security issues it creates. If you are using Node, you can use the built in `fs` module to read and write from a file. – mattdevio Dec 30 '17 at 10:26
  • I developing with Angular, I have in a component a file that I would like to read – Raphael Dec 30 '17 at 10:33

2 Answers2

1

If you're writing browserside JS

You can't just simply read a file. The JS is running on your browser, and you need to think about where you're getting that file from.

If the file is on a server, you need to fetch that file from the server first by making a request for it.

If you're reading a file on the user's computer, you're gonna be using the File API on the browser to allow the user to select that file.

If you're writing backend JS

Assuming you're using NodeJS, you can conduct file operations like you would with other programming languages. Check out the fs module

Community
  • 1
  • 1
0

If i understand you correct, you can read it as text like this:

function readFile(file){
    var raw = new XMLHttpRequest(); // create a request
    raw.open("GET", file, false); // open file
    raw.onreadystatechange = function (){ // file is ready to read
        if(raw.readyState === 4){
            if(raw.status === 200 || raw.status == 0){
                var allText = raw.responseText;
                alert(allText); // can be also console.logged, of course.
            }
        }
    }
    raw.send(null); // return control
}

usage:

readFile('link.html')

I solved this issue thankfully to this question.

Animus
  • 665
  • 12
  • 24
  • I have this message when using XMLHttpRequest: [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. – Raphael Dec 30 '17 at 10:39
  • This solution works for me on v5, I can give you a link to the project sample. Otherwise please provide more info, like module and component files. https://www.dropbox.com/sh/js39skue1sz1ovq/AAAbBGStl6gn9nLfkHD_oAVna?dl=0 – Animus Dec 30 '17 at 10:53