如何逐行提取单个元素并在Javascript中存储在数组中?

时间:2017-12-12 03:00:48

标签: javascript arrays node.js google-maps

我有一个文本文件' mytext.txt'使用IP和一些文本用逗号分隔不同的行 -

24.16.153.165:51413,abc
67.185.72.127:51413,xyz
69.247.183.46:63303,pqr
130.56.220.16:6881,def

我想用JavaScript将数据存储在数组中,以便在地图上绘制它们。我找到了一种方法来使用静态数组 -

var map = new google.maps.Map(document.getElementById('map'), googleMap);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(infowindow, "closeclick", function() {
                map.fitBounds(latlngbound);
                map.panToBounds(latlngbound)
            })
var ipArray = ["70.177.167.189", "123.135.107.115", "123.135.107.115", "123.135.107.115", "123.135.107.115", "122.182.6.19", "24.19.187.145", "24.19.187.145", "27.251.20.130", "27.251.20.130"];
ipArray.forEach((ip) => {
     addIPMarker(ip);
              })
    } catch(e){
        //handle error
}

有人可以在从文本文件中提取IP后告诉我如何操作吗?它应该是一个相当简单的逻辑,但我对JavaScript并不是很熟悉。谢谢!

2 个答案:

答案 0 :(得分:0)

如果您在服务器或其他网址上有文件,则此功能有效。

function loadDoc() {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = this.responseText;
        var data = myObj.split(/\n/g);
        var data_ip = [];
        for(item in data)
        {

            var ip = data[item].split(/,/g);
            data_ip.push(ip[0]);
        }

        console.log(data_ip);
    }
};
xmlhttp.open("GET", "file.txt", true);
xmlhttp.send();
}

这适用于本地存储的文件。

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 myObj = rawFile.responseText;                
                var data = myObj.split(/\n/g);
                var data_ip = [];
                for(item in data)
                {

                    var ip = data[item].split(/,/g);
                    data_ip.push(ip[0]);
                }

                console.log(data_ip);
            }
        }
    }
    rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");

答案 1 :(得分:0)

要从系统中读取文件,您需要使用Node提供的fs(文件系统)模块。您无需执行任何npm install

JavaScript文件:

const fs = require('fs');

const mapData = fs.readFileSync(//path to file here);

// do things with the data like your ip mapping, etc...

我在示例中使用了fs.readFileSync()函数,但您需要阅读文档并了解哪种方法最适合您的应用程序。

文档: https://nodejs.org/api/fs.html