On the server, there is a text file. Using JavaScript on the client, I want to be able to read this file and process it. The format of the file on the server cannot be changed.
How can I get the contents of the file into JavaScript variables, so I can do this processing? The size of the file can be up to 3.5 MB, but it could easily be processed in chunks of, say, 100 lines (1 line is 50-100 chars).
None of the contents of the file should be visible to the user; he will see the results of the processing of the data in the file.
You cannot read server side data through Javascript unless you have a connection to the server. Whatever Javascript code that runs on the client's browser will remain on their browser only, even if both are ran on the same computer.
Use the fs. readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8'). split('\n') . The method will return the contents of the file, which we can split on each newline character to get an array of strings.
JavaScript cannot typically access local files in new browsers, but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.
You can use hidden frame, load the file in there and parse its contents.
HTML:
<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>
JavaScript:
<script type="text/javascript"> function LoadFile() { var oFrame = document.getElementById("frmFile"); var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML; while (strRawContents.indexOf("\r") >= 0) strRawContents = strRawContents.replace("\r", ""); var arrLines = strRawContents.split("\n"); alert("File " + oFrame.src + " has " + arrLines.length + " lines"); for (var i = 0; i < arrLines.length; i++) { var curLine = arrLines[i]; alert("Line #" + (i + 1) + " is: '" + curLine + "'"); } } </script>
Note: in order for this to work in Chrome browser, you should start it with the --allow-file-access-from-files flag. credit.
Loading that giant blob of data is not a great plan, but if you must, here's the outline of how you might do it using jQuery's $.ajax()
function.
<html><head> <script src="jquery.js"></script> <script> getTxt = function (){ $.ajax({ url:'text.txt', success: function (data){ //parse your data here //you can split into lines using data.split('\n') //an use regex functions to effectively parse it } }); } </script> </head><body> <button type="button" id="btnGetTxt" onclick="getTxt()">Get Text</button> </body></html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With