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?

3
  • 3
    In what environment? From a browser? NodeJS? Windows Metro app? Something else? Commented Dec 30, 2017 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. Commented Dec 30, 2017 at 10:26
  • I developing with Angular, I have in a component a file that I would like to read Commented Dec 30, 2017 at 10:33

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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.
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. dropbox.com/sh/js39skue1sz1ovq/AAAbBGStl6gn9nLfkHD_oAVna?dl=0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.