http.get( ) 方法和 var request = require('request') 有什么区别

what is difference between http.get( ) method and var request = require('request')

我是 node JS 的新手,在 learnyounode 的 nodeJS 练习 8 中,我的解决方案产生相同的 require result.I 很困惑何时使用 http.get 和 Request

目标: 编写一个程序,向提供给您的 URL 执行 HTTP GET 请求
作为第一个命令行参数。从服务器收集所有数据(不是
只是第一个 "data" 事件),然后向控制台写入两行
(标准输出)。

你写的第一行应该只是一个代表数字的整数
从服务器接收到的字符数。第二行应该包含
服务器发送的完整字符串。

官方解决方案

var http = require('http')
var bl = require('bl')

http.get(process.argv[2], function (response) {
    response.pipe(bl(function (err, data) {
        if (err)
            return console.error(err)
        data = data.toString()
        console.log(data.length)
        console.log(data)
    }))
})

我的解决方案

var request=require('request')
request(process.argv[2],function(err,response,body){
console.log(body.length);
console.log(body);
})

来自nodeJS documentation

Since most requests are GET requests without bodies, Node.js provides this convenience method. The only difference between this method and http.request() is that it sets the method to GET and calls req.end() automatically. Note that response data must be consumed in the callback for reasons stated in http.ClientRequest section.

所以,这到底意味着什么,您可以毫无问题地按照自己的方式进行。但是 request 不是节点本身附带的模块,它是一个使开发人员更容易进行 http(s) 请求的模块。所以我在这里猜测,您正在学习 NodeJS 而不是使用第三方应该是正确的选择。

我不熟悉 request 但它似乎只是一个 npm package that wraps the functionality of the standard library. You can use both but I would suggest reading through the documentation of http.get and request 如果你发现标准库函数 (http.get) 就足够了根据您的需要,我看不出您应该使用请求包的理由。