1

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!

2 Answers 2

1

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
    }
);
Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

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.