(in js) reading the contents of a local text file into a string

47 Views Asked by At

(after 20 hours of failing with the many clever code snippets already posted on Stack Overflow, as a js beginner .. )

my project needs a conceptually simple js function, something like:

var sOut = '';
var f = fname;         // fname is one of a dozen very small text files, created in the same local directory 
function readfile( fname ) {
  ...??
  ...??
}

readfile(f); 

after the call to readfile(), as sketched here, sOut should contain the contents of fname

I've tried around ten very different snippets, inserted into my html/css/js project, in the form of functions like the skeleton shown above, using "alert" to monitor the function's internal code flow, by using Edge as browser and invoking my project by selecting its .html and "Open With" "Microsoft Edge".

But the simplest of these snippets are designed to immediately display text, rather than what I need, to save text for later display. These do return smoothly to my project code, but without any result that, for example, displays the file's contents with an alert() call. Others seem to require that I install and learn about deeper client/server/database stuff like Node.js, fetch, addEventListener, etc. -- not surprising that when I simply include and invoke these code snippets, my whole application simply freezes. Glad to learn, but this function looks like all I need to finish my application, and rabbit holes do take time!

Thanks for reading, and with enormous gratitude for a suggestion that works.

0

There are 0 best solutions below