Raphael
Raphael

Reputation: 719

Javascript, Typescript, Angular 5 - Open and read file

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?

Upvotes: 2

Views: 9580

Answers (2)

Animus
Animus

Reputation: 833

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.

Upvotes: 0

boysimple dimple
boysimple dimple

Reputation: 199

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

Upvotes: 1

Related Questions