简体   繁体   中英

Read Text File in JavaScript Without Input

Hopefully this is a straightforward question, but I want to read a text file that is in the same location as my .js file using JavaScript. I've read about the FileReader and sort of understand the API there, but all of the examples I've seen use <input type="file" /> as a way of capturing the File object necessary to be read by the FileReader .

In addition, how difficult would it be to read a text file that contains JSON data? Ideally I just want to store some data as JSON and read it in using JavaScript. Any help would be greatly appreciated. Thanks!

So I've gotten some good responses, but I'm going to expand my question a little. Thank you so far for what you've provided!

I'm using TypeScript, so jQuery is a little tricky (using the projection). But I found out about XMLHTTPRequest . Is this also a good solution to this problem? Thanks!

You can just open the location of the text file as a url. The file will be sent to the browser with a normal GET-request. When you want to read JSON files I would recommend to use JQuery. JQuery has a build in function called getJSON, it just returns the data from the JSON file as a JS object

$.getJSON(
    url,
    function(data) {
       //json is converted in 'data' object
    }
);

Are you running your Javascript with Node.js or in a browser? Do you want to read in a file provided by the user or one that your script already knows about? I think FileReader is for reading files stored on the user's computer, which is why the examples use an <input type="file" /> tag.

Running locally with Node.js (not in a browser), I read in JSON files like this:

var fileString = fs.readFileSync("./path/to/file/" + filename, {encoding: 'utf8'});
var fileObject = JSON.parse(fileString);

In a browser, you can read in files like this using jQuery:

var file_url = 'http://url/to/file/' + filename;
$.ajax({
    url: file_url,
    dataType: "json",
    success: function (json_response) {
        // Process the json_response
    },
    error: function () {
        // Handle the error.
    }
});

If you end up reading your file in some other way, you can still use JSON.parse() in the browser. I hope that helps!

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