admin管理员组

文章数量:1306037

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]

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]
Share Improve this question edited Dec 5, 2016 at 16:47 AntGeorge asked Jun 19, 2015 at 18:15 AntGeorgeAntGeorge 631 gold badge1 silver badge9 bronze badges 4
  • 1 local as in, on your filesystem or local on your web server that is serving the .js file? – Brendan Hannemann Commented Jun 19, 2015 at 18:18
  • 2 Are you using node.js or are you trying to do this in the browser? – Mulan Commented Jun 19, 2015 at 18:18
  • 1 Check this how to read text file in javascript – Sergey Maksimenko Commented Jun 19, 2015 at 18:22
  • @SergeyMaksimenko Thank you It work but i take a syntax error in test.txt – AntGeorge Commented Jun 19, 2015 at 18:55
Add a ment  | 

3 Answers 3

Reset to default 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

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>

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]

本文标签: Javascript create array from local filetxtStack Overflow