2

I have this text file in the same directory with my javascript program:

test.txt

1
2
3
4
5

I want to load the data in array. So at the end i will have a array variable as follow:

[1,2,3,4,5]
4
  • 1
    local as in, on your filesystem or local on your web server that is serving the .js file? Commented Jun 19, 2015 at 18:18
  • 2
    Are you using node.js or are you trying to do this in the browser? Commented Jun 19, 2015 at 18:18
  • 1
    Check this how to read text file in javascript Commented Jun 19, 2015 at 18:22
  • @SergeyMaksimenko Thank you It work but i take a syntax error in test.txt Commented Jun 19, 2015 at 18:55

3 Answers 3

2

You can use XMLHTTPRequest to load the text from file, like jQuery does, then you can put it something like this:

var array = [];
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var text = xmlhttp.responseText;
        // Now convert it into array using regex
        array = text.split(/\n|\r/g);
    }
}
xmlhttp.open("GET", "test.txt", true);
xmlhttp.send();

this way you will get in array form, the text from test.txt file.

I am assuming test.txt in same folder as script does

Sign up to request clarification or add additional context in comments.

1 Comment

why not use split with regex direct, instead of replacing line breaks with comma?
2

try this way

<script>
fs.readFile('test.txt',"utf-8",function(err,data){
        if(err) throw err;
        var array = Array.from(data) //convert char array
        console.log(array)

</script>

Comments

1

This is your text as a string when you get a text file:

var text = "1\n2\n3\n4\n5";

You need to use String.prototype.split to create an array:

text = text.split("\n");

After you will get an array:

console.log(text); // [1,2,3,4,5]

4 Comments

Could you tell me, please, what is wrong with this approach? Why you voted against?
I don't know who voted down but i think because you didn't explain how get a text file as a string.
Thanks, but nobody asked that.
yes, the question is about how to read the data in from a local text file. Not how to split an already existing string into an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.