Yes I've looked already at internet, 3 different queries, 5 pages each, looked on StackOverflow, then its marked as offtopic question, searched through here, answer related like sun and pancakes.

My question is, how can I store content of file into variable?
While I was Googling I came on this website few times, and script did not work.
Could anybody help?

How can I store content of "foo.txt" into "xyz" variable?

(Sorry for such LQ post, just searching for an answer for hour, literally)

Dani AI

Generated

There are two distinct cases to resolve: a text file served by the website, and a file sitting on a visitor’s local disk. Browser JavaScript cannot arbitrarily open local files; the file must either be served over HTTP by the site or explicitly handed to the page by the user. Attempts to use ActiveX only work in legacy IE and are brittle—this is why and warned against it. ’s suggestion to use AJAX (or jQuery) is correct for files the server can serve.

If the file is on the server, fetch the file over HTTP and store its text in a variable. Example (modern, promise/async style):

async function loadText(path) {
  const res = await fetch(path);
  if (!res.ok) throw new Error('HTTP ' + res.status);
  return await res.text();
}

loadText('/foo.txt').then(text => {
  // `text` now contains the file contents
  document.getElementById('divid').textContent = text;
}).catch(console.error);

If the file is on the user’s machine, use the HTML5 File API + FileReader so the user explicitly grants access:

document.querySelector('#fileInput').addEventListener('change', e => {
  const f = e.target.files[0];
  if (!f) return;
  const r = new FileReader();
  r.onload = ev => {
    const content = ev.target.result; // file contents here
  };
  r.readAsText(f);
});

Troubleshooting: requests must be same‑origin or the server must enable CORS; running pages from file:// can block fetch/XHR—start a simple local server for testing (e.g., python -m http.server). Check DevTools for 404/CORS errors and ensure the server serves the file (text/*). For more API detail see Using Fetch, FileReader, and CORS basics.

Recommended Answers

All 12 Replies

The only way I can think of doing it is to submit a file (via ajax or iframe) and then the callback or whatever method you prefer sets the value of a variable.

Javascript is abstracted from the OS/File System for security reasons. The user needs to "give" you the file before you can do anything with it. However, you are setting a "cookie" or local storage variable, you may be able to do something there. However, I think it would be fairly limited due to size contraints and the fact that you need to set the file before you can edit it.

Perhaps if you explained what you were trying to do someone can give a good starting point for research or code example?

Member Avatar for Member #905211

Is this a file on the local computer or on the server?

For reading a textfile off of a server you can easily do this using jQuery.
http://api.jquery.com/load/

If you want to read the file from the local machine, and you are good with using HTML5, then you can look at this article (just make sure your browser supports it).
http://www.html5rocks.com/en/tutorials/file/dndfiles/

Why is everyone including ASP.net and Ajax?
There is file, a website file that I want to include to main page.
And I need content of file as variable to be able to change content by .js file.

This local file, but. But I mean JS in website design, not a file to double click on.

I saw no editon button, this is script I am including as JS into HTML document, and no result.

var fso = new ActiveXObject("Scripting.FileSystemObject");
fileObj = fso.GetFile("foo.txt");

alert ("Before");
alert (fileObj);
alert ("After");

@edit This post has edit button, but not earlier written one.

ActiveX objects, as far as I know, requires some sort of Microsoft intervention or emulation... that is, you probably need to do more than just create an active X object in script.

I assume, then, that you are running this in IE and on Windows, or are familliar with this type of object (I am not).

However, a quick lookup to MSDN says:
http://msdn.microsoft.com/en-us/library/2z9ffy99

Looks like you are close. GetFile seems to require an absolute path. Try instead:

fileObj = fso.GetFile("C:\foo.txt"); //this assumes the file lives on the C:\ drive.

Hope that helps.

Alternatively, as I had suggested above (and others also tried to build upon), is you upload a file to your server using a traditional file input (<input type="file" name="upload" .... />), and let the server process the file for you, then spit out a return value that can be JSON encoded or any other encoding you like, and then store that in a javascript variable. This would be cross browser / cross platform, and allow you to do a bit more with the data coming in.

Ryan

Dear Ryan,

Are we surely talking about same Javascript? I don't need things to upload. The .js file is in same folder as .txt file. The script I want make work is:

function thefunction() {
    document.getElementById("divid").innerHTML = content_from_file;
}

But I don't know how to set content_from_file.

Does that make it anysome clearer?

Member Avatar for Member #905211

Seriously, use jQuery. It's a javascript library and is cross browser and ends up being one line.

Seriously, use jQuery. It's a javascript library and is cross browser and ends up being one line.

How do I retrieve it? I see how it loads, and how to change content of div to content of file. But I need content of file, as variable.

Member Avatar for Member #905211

ok, use $.get instead http://api.jquery.com/jQuery.get/ or use load for a div that is hidden and when the load is complete put the contents of the div into a variable.

Member Avatar for Member #120589

Why is everyone including ASP.net and Ajax

AFAIK you need to use Ajax to get the content, as previously mentioned. Avoid solutions using ActiveX as they will only work for IE.

If you just want the contents of a text file, then use something like jQuery (also as previously mentioned). A quick look gave me this...

http://stackoverflow.com/questions/196498/how-do-i-load-the-contents-of-a-text-file-into-a-javascript-variable

Funny what's out there...

This is my pre-AJAX (1997-, technology) a live demo at:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.