NodeJS入门 0x2 异步编程(1)回调

    在 Node 的世界里流行两种响应逻辑管理方式:回调和事件监听。

用回调处理一次性事件

    回调是一个函数,它被当作参数传给异步函数,用来描述异步操作完成之后要做什么。 

    这里用一个简单的 HTTP 服务器演示回调的用法,让它实现如下功能:
     异步获取存放在 JSON 文件中的文章的标题;
     异步获取简单的 HTML 模板;
     把那些标题组装到 HTML 页面里;
     把 HTML 页面发送给用户。

最终结果

    JSON 文件(titles.json)

[
	"Kazakhstan is a huge country... what goes on there?",
	"This weather is making me craaazy",
	"My neighbor sort of howls at night"
]

     HTML 模板文件(template.html)

<!doctype html>
<html>
	<head></head>
	<body>
		<h1>Latest Posts</h1>
		<ul><li>%</li><ul>
		<!--%会被替换-->
	</body>
</html>

    JS文件(blog_recent.js)

const http = require('http');
const fs = require('fs');
//创建HTTP服务器并用回调定义响应逻辑
http.createServer((req,res)=>{
  if(req.url=='/'){
	//读取JSON文件并用回调定义如何处理其中的内容
    fs.readFile('./titles.json',(err,data)=>{
	  //如果出错,输出错误日志,并给客户端返回“Server Error”
      if(err){
        console.error(err);
        res.end('Server Error');
      }else{
		//从JSON文本中解析数据
        const titles = JSON.parse(data.toString());
		//读取HTML模板,并在加载完成后使用回调
        fs.readFile('./template.html',(err,data)=>{
          if(err){
            console.error(err);
            res.end('Server Erroor');
          }else{
            const tmpl = data.toString();
			//组装HTML页面以显示博客
            const html = tmpl.replace('%',titles.join('</li><li>'));
            res.writeHead(200,{'Content-Type':'text/html'});
			//将HTML页面发送给用户
            res.end(html);
          }
        });
      }
    });
  }
}).listen(8000,'127.0.0.1');

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值