简体   繁体   中英

Reading Text Files from Local Directory in Javascript

I'm working on a Chrome extension and I want to take data from text files that will be in the same directory as the Javascript files with the functionality (that is, read the text files in as strings and use those for analysis of some kind). I'm pretty new to Javascript, so I've been trying to figure out how to do this--it seems that FileReader won't work since the user isn't uploading the files I'm using, and I'm not sure how XML HTTPRequest would be useful in this situation. Thank you!

tldr; I want to read text files in the same directory as a Javascript file in as strings.

update: The file is not a file from the user's file system, but one that's packed with the extension! So the folder that contains the HTML file and the Javascript file will also contain the text files.

Someone correct me if I'm wrong but as far as I know this is not possible in JavaScript due to security concerns.

If it were, a web page could grab any file on your file system without your consent or without you knowing. This is a major security concern so I dont believe it is possible.

A user must be given the option to choose a file from their file system knowingly.

You can try:

function readTextFile(file)
{
   var rawFile = new XMLHttpRequest();
   rawFile.open("GET", file, false);
   rawFile.onreadystatechange = function ()
    {       
         var allText = rawFile.responseText;
            alert(allText);

    }

 rawFile.send(null);
}

And specify file:// in the same directory as a Javascript file

Due to browser security standard you cant access any file from your (HDD) at all.

Please try using this chrome API https://developer.chrome.com/apps/app_storage#filesystem-manifest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM