Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read file content in a javascript variable?

Tags:

javascript

I got a small script to split the text inside 'var foo' after every 4 characters. It is working fine. but my actual data is in a text file say 'a.txt'. How do I take this entire file text in 'var foo'. and write the split output to another text file?

var foo = "this is sample text !!!"; 
var arr = [];
for (var i = 0; i < foo.length; i++) {
    if (i % 4 == 0 && i != 0)
        arr.push(foo.substring(i - 4, i));
    if (i == foo.length - 1)
        arr.push(foo.substring(i - (i % 4), i+1));          
}
document.write(arr);
console.log(arr);
like image 352
BioDeveloper Avatar asked Apr 25 '13 12:04

BioDeveloper


People also ask

How do I load a file into JavaScript?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

Can JavaScript read and write files?

writeFile() methods are used to read and write of a file using javascript. The file is read using the fs. readFile() function, which is an inbuilt method. This technique reads the full file into memory and stores it in a buffer.

How do you find if a string is present in a text file in JavaScript?

Use the fs. readFileSync() method to read the file. Use the includes() method to check if the string is contained in the file. The includes method will return true if the string is contained in the file.


2 Answers

To get the content of the file you need to select a file using an input tag.

<!DOCTYPE html>
<head>
  <meta charset="UTF-8">
</head>
<body>
  <input id="input" type="file" accept="text/plain">
  <script src="script.js"></script>
</body>

A good moment to read the content of the file is in the change event.

const input = document.querySelector("#input");

input.addEventListener("change", () => {
  const file = input.files.item(0);
});

To read the content of the file as a string you need to convert it.

function fileToText(file, callback) {
  const reader = new FileReader();
  reader.readAsText(file);
  reader.onload = () => {
    callback(reader.result);
  };
}

The content of the file as a string will be available to the the callback function. You can create a link and use the click event to download the string into a text file.

function save(content, fileName, mime) {
  const blob = new Blob([content], {
    tipe: mime
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = fileName;
  a.click();
}

Here is the complete code

const input = document.querySelector("#input");

input.addEventListener("change", () => {
  const file = input.files.item(0);
  fileToText(file, (text) => {
    save(text, "fileName.txt", "text/plain");
  });
});

function fileToText(file, callback) {
  const reader = new FileReader();
  reader.readAsText(file);
  reader.onload = () => {
    callback(reader.result);
  };
}

function save(content, fileName, mime) {
  const blob = new Blob([content], {
    tipe: mime
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = fileName;
  a.click();
}
<!DOCTYPE html>

<head>
  <meta charset="UTF-8">
</head>

<body>
  <input id="input" type="file" accept="text/plain">
  <script src="script.js"></script>
</body>

You can read more about manipulating files in JavaScript here: https://www.html5rocks.com/en/tutorials/file/dndfiles/

like image 164
Rodrigo5244 Avatar answered Nov 03 '22 15:11

Rodrigo5244


Solution to this helped me :

How do I load the contents of a text file into a javascript variable?

var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
like image 33
cansu Avatar answered Nov 03 '22 14:11

cansu