Lea*_*ott 5 javascript httprequest node.js
我的任务是从http://services.swpc.noaa.gov/text/ace-swepam.txt获取数据并将其拆分/排序为有用的东西.首先,我正在尝试将数据拆分为类别,以便我可以在chart.js中使用或稍后使用,但是当我尝试打印字段时,它只是以[]的形式出现.
var options = {
host: 'services.swpc.noaa.gov',
path: '/text/ace-swepam.txt',
port: 80,
method: 'POST'
};
var req = http.request(options, function (res) {
res.on('data', function (chunk) {
// console.log('BODY: ' + chunk);
results += chunk.toString();
//split results into an array by each new line
lines = results.split("\n");
//delete header lines
lines.splice(0, 18);
if (lines.length <= 20) {
return;
}
console.log(lines);
});
res.on('end', function (e) {
callback();
});
});
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
req.end();
function callback() {
for (var line in lines) {
var x = [];
x = lines[line].split(" ");
var statuscode = x[14];
if (statuscode == 0) {
if (lines[line].indexOf('-') === -1) {
year.push(x[0]);
month.push(x[1]);
day.push(x[2]);
time.push(x[4]);
statusno.push(statuscode);
proton.push(x[22]);
bulksp.push(x[28]);
iontemp.push(x[33]);
}
}
}
// console.log(year, month, day, time, statusno, proton, bulksp, iontemp)
}
Run Code Online (Sandbox Code Playgroud)
数据行似乎不是制表符分隔的。我希望它们是固定长度的。
这是我收到的第一行。“2015年08月18日1708 57252 61680 0 2.6 45”
而不是尝试按选项卡拆分此行。
fields = line.split("\t");
Run Code Online (Sandbox Code Playgroud)
创建每个字段长度的数组并使用 substring 方法拆分它。
这是解析返回数据的完整代码。它给出了 119 行,或者其中 6-7 行的状态!=0(因此被跳过)。您的变量每个都有 112 个条目。
res.on('data', function (chunk) {
var fieldLengths = [0, 4, 7, 10, 16, 24, 32, 37, 48, 59, 72];
// console.log('BODY: ' + chunk);
results += chunk.toString();
//split results into an array by each new line
lines = results.split("\n");
// for me, the first "chunk" is incomplete. Throw it away and just use the second chunk.
if (lines.length <= 20) {
return;
}
//delete header lines
lines.splice(0, 18);
for (var line in lines) {
console.log("entry: " + lines[line]);
//split into data fields
var lineText = lines[line];
var fields = [];
for (var i = 0; i <= fieldLengths.length -1; i++) {
fields.push(lineText.substring(fieldLengths[i], fieldLengths[i + 1]));
}
//if there are no problems (status code 0)
//add the data to their respective fields
if (fields[6] == 0) {
year.push(fields[0]);
month.push(fields[1]);
day.push(fields[2]);
time.push(fields[3]);
statusno.push(fields[6]);
proton.push(fields[7]);
bulksp.push(fields[8]);
iontemp.push(fields[9]);
}
}
});
res.on('end', function (e) {
console.log(year);
});
Run Code Online (Sandbox Code Playgroud)
});
如果您使用 Visual Studio(免费社区版即可)并添加 Visual Studio 的节点工具,则很容易调试。
如果数据不太正确,请告诉我。我理解您想要做什么,并且可以在必要时调整代码。
| 归档时间: |
|
| 查看次数: |
191 次 |
| 最近记录: |