我仍在尝试掌握这一点,但这让我感到困惑。所以我使用 http.get 和带有 bl 模块的管道,我希望它更改内容,以便我可以在函数之外使用它,为什么不起作用?我认为使用 var 它将在我的文件中是全局的,这将允许我更改它。
var http = require('http');
var bl = require('bl');
var url1 = process.argv[2];
var content;
http.get(url1, function(response){
response.pipe(bl(function(err,data){
return data.toString();
}));
});
console.log(content.length);
console.log(content);
最佳答案
您是否尝试修改内容
?您永远不会向它分配任何内容,然后尝试同步访问它(这几乎肯定会在 get
完成之前发生)。我假设你想做的事情更像是:
...
var content;
http.get(url1, function(response){
response.pipe(bl(function(err,data){
content = data.toString();
console.log(content.length);
console.log(content);
}));
});
关于javascript - 具有响应和 http 方法的 Node JS 变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25511849/