node.js快速入门: learnyounode题目解答,http collect ,async/await in node...etc

本文介绍了使用learnyounode学习Node.js的过程,包括http client、http collect、异步处理等练习,讲解了Node.js中http模块的使用、异步编程技巧,并分享了在实践中遇到的问题及解决方案。
摘要由CSDN通过智能技术生成

learnyounode是一套很棒的node入门课程,由浅到深,引导和提示都很全面,以编程的方式学习node的核心功能。推荐萌新们来一发~~~

安装与教程参考

我是在这个网上看到的各种课程,感觉还挺全面的
nodeschool: 教你 Web 开发技能的开源课程,自学或者参加一个附近的教学活动

这是官方的github地址:
learnyounode 的 github

小伙伴也可以去参考这个人的博客,写的很全面:
learnyounode Unofficial Companion

用npm sudo安装learnyounode:

sudo npm install learnyounode -g

终端页面长这样:
这里写图片描述


http client: 为何有两个error事件

Exercise 7 of 13

蔺相如司马相如,名相如实不相如。

题目要求是利用http模块,以字符串的形式输出get到的数据。official solution大概长这样:

http.get(process.argv[2], function (response) {
  response.setEncoding('utf8')
  response.on('data', console.log)
  response.on('error', console.error)
}).on('error', console.error)  

这里有个小小的疑问,那就是error事件处理了两次,显然,第1个error是response的error 后面on的error是get方法的。那么,它们分别代表什么含义呢?

If any error is encountered during the request (be that with DNS resolution, TCP level errors, or actual HTTP parse errors) an ‘error’ event is emitted on the returned request object.

如果请求过程中遇到任何错误(DNS 解析错误、TCP 级的错误、或实际的 HTTP 解析错误),则在返回的请求对象中会触发 ‘error’ 事件。 对于所有的 ‘error’ 事件,如果没有注册监听器,则抛出错误。

Since most requests are GET requests without bodies, Node 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.

也就是说,http的get方法就是http.request() 的语法糖,无需传递数据(body ),会自动调用req.end(),两者没有本质区别。在错误处理上,应该也是一样的。

来看一段中文官网给的代码例子

http.get('http://nodejs.org/dist/index.json', (res) => {
  const { statusCode } = res;
  const contentType = res.headers['content-type'];

  let error;  
  if (statusCode !== 200) {
    error = new Error('请求失败。\n' +
                      `状态码: ${statusCode}`);
  } else if (!/^application\/json/.test(contentType)) {
    error = new Error('无效的 content-type.\n' +
                      `期望 application/json 但获取的是 ${contentType}`);
  }
  if (error) {
    console.error(error.message);
    // 消耗响应数据以释放内存
    res.resume();
    return;
  }

  res.setEncoding('utf8');
  let rawData = '';
  res.on('data', (chunk) => { rawData += chunk; });
  res.on('end', () => {
    try {
      const parsedData = JSON.parse(rawData);
      console.log(parsedData);
    } catch (e) {
      console.error(e.message);
    }
  });
}).on('error', (e) => {
  console.error(`错误: ${e.message}`);
});

总结下:

  • get阶段的error:
    比较低层的错误,比如请求没有发出去,网络原因,超时,中途取消了请求等等,或者像文档解释的一样,dns解析,传输层错误,或者http解析错误。

  • response的error:
    从以上代码可以看到,4XX,5XX之类的错误,或者拿到的content-type不一样都会归入response的error,当然也可能是php报错,虽然是2XX的,但拿到的resp不是想要的。


http collect (Exercise 8 of 13)

从这里开始上代码了

我做到

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值