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
3 Answers
Reset to default 2You 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
版权声明:本文标题:Javascript create array from local file.txt - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741811950a2398848.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论