How to Read a Text File from Server Using JavaScript

how to read text file in folder with javascript

JavaScript in browser doesn't give you direct access to file system.
What you did is just pass a string to your function and call text() on it. Sadly it doesn't work like that.

Here are two workarounds I know of:

1. fetch api

If you have an http server serving your files then you make a request using fetch() to obtain its content in JS. Read the docs here :

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Note that it won't work on pages loaded with file:// URI scheme. You need http(s). If you have python installed run python -m http.server 8000 in directory containing files to be served.

2. FileReader

If the file is to be selected by user as input to a form then you can use FileReader

Have a look these links:
webdev has great explaination for this

https://web.dev/read-files/

also see the docs

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

How to read a local text file in the browser?

You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a Webserver)

function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}

And specify file:// in your filename:

readTextFile("file:///C:/your/path/to/file.txt");

Read text file in JavaScript from server

I created a basic example using just Javascript, starting with the example that I linked in the comments above. Just read in the text file using FileReader and create a loop in the onload function, where you parse out the records that you want. I based my file spec off of wikipedia, using the Example 6.

Result: https://jsfiddle.net/1sce9mv6/6/

Javascript:

   document.getElementById('file').onchange = function() {

var file = this.files[0];

var reader = new FileReader();
reader.onload = function(progressEvent) {
// Entire file for debugging
//console.log(this.result);

// By lines
var lines = this.result.split('\n');

console.log('File read.');

//Check if this is an m3u file
if (lines[0].includes("#EXTM3U")) {
console.log("File header found!");

//Go through each line
for (var line = 1; line < lines.length; line++) {

//Process line
if (lines[line].includes("#EXTINF")) {

//print full line
console.log(lines[line]);

//split each line into the elements
var currentLine = lines[line].substring(7).split(',');
console.log("Runtime: " + currentLine[0]);
console.log("Song:" + currentLine[1]);
} else {
continue;
}
}
} else {
console.log(lines[0]);
console.log("Not m3u file...");
}
};
reader.readAsText(file);
};

HTML:

<input type="file" name="file" id="file">

References:

  • How to use Javascript to read local text file and read line by line?
  • https://en.wikipedia.org/wiki/M3U#Examples

read a file then display in on client-side

JavaScript running in the web browser cannot have access to the file system on the server.

Imagine if you could open your browser's developer tools while using your online banking and just start reading files from your bank's hard disk!

If you want to get a file from the server to client-side JS you need to do something on both sides.

On the server you need to make the file available over HTTP(S). This could be as simple as putting the file somewhere under the DocumentRoot of the web server.

On the client you need to make an HTTP request. You can do that using the fetch API, the XMLHttpRequest API or a library that wraps one of them such as Axios.

Read / Write txt file on server using only javascript without involving any server side language

Only if JavaScript is your server side language (e.g. with Node.JS).

Servers don't let you write files to them by default. That would be a horrible security problem.



Related Topics



Leave a reply



Submit