Javascript, Typescript, Angular 5 - Open and read file

你说的曾经没有我的故事 提交于 2021-02-16 14:49:49

问题


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?


回答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




回答2:


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.



来源:https://stackoverflow.com/questions/48033006/javascript-typescript-angular-5-open-and-read-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!