【发布时间】:2015-04-29 05:18:06
【问题描述】:
在learnyounode上做教程,遇到如下问题。来自描述:
您将获得三个 URL 作为前三个命令行参数。您必须收集每个 URL 提供给您的完整内容并将其打印到控制台 (stdout)。您不需要打印出长度,只需将数据作为字符串;每个 URL 一行。问题是您必须按照作为命令行参数提供给您的 URL 的顺序打印它们。
似乎有时我会为提供的其中一个 url 得到重复的结果,但是,在其他时候,代码通过了本教程作者创建的测试...
http = require('http')
var urls = process.argv.slice(2)
var output = []
// allocate space for the contents of each response.
output.length = urls.length
var counter = 0
urls.forEach( function(url, index, array) {
http.get(url, function (response) {
stream = ''
response.on("error", function (error) {
console.error('There was an error:', err)
})
response.on("data", function (data) {
stream = stream + data.toString();
})
response.on("end", function () {
// it seems that this even fires multiple times for the same url (?)
output.splice(index, 1, stream);
counter += 1;
if (counter == array.length) {
output.forEach( function (element, index, array) {
console.log(element);
})
}
})
})
})
【问题讨论】:
标签: javascript node.js