一生一世学坛

 找回密码
 立即注册
搜索
查看: 8888|回复: 0
打印 上一主题 下一主题

Nodejs中回调的用法

[复制链接]

334

主题

385

帖子

6816

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
6816
跳转到指定楼层
楼主
发表于 2019-4-2 15:52:57 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
Nodejs中回调的用法:
新建blog_recent.js文件:
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {//创建http服务器,并用回调定义响应逻辑
  if (req.url == '/') {
    fs.readFile('./titles.json', (err, data) => {//读取json文件,并用回调处理读取到的数据
      if (err) {//如果出错,打印日志,给客户端发送错误消息
        console.error(err);
        res.end('Server Error');
      } else {
        const titles = JSON.parse(data.toString());//从json文本解析数据
        fs.readFile('./template.html', (err, data) => {//读取模板,并用回调处理模板替换
          if (err) {
            console.error(err);
            res.end('Server Error');
          } else {
            const tmpl = data.toString();
            const html = tmpl.replace('%', titles.join('</li><li>'));
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(html);//讲html数据发送给用户
          }
        });
      }
    });
  }
}).listen(8000, '127.0.0.1');

新建template.html文件:
<!doctype html>
<html>
  <head></head>
  <body>
    <h1>Latest Posts</h1>
    <ul><li>%</li></ul>
  </body>
</html>

新建tiles.json文件:
[
  "Kazakhstan is a huge country... what goes on there?",
  "This weather is making me craaazy",
  "My neighbor sort of howls at night"
]

然后运行服务:
node blog_recent

然后在浏览器访问:http://localhost:8000/  可以看到json中的内容。

上述代码就是获取json文件内容,渲染到html中%的位置。

上述代码中的回调嵌套了3层。

把回调嵌套做成命名的函数,可以使代码清晰一些:
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
  getTitles(res);
}).listen(8000, '127.0.0.1');

function getTitles(res) {
  fs.readFile('./titles.json', (err, data) => {
    if (err) {
      hadError(err, res);
    } else {
      getTemplate(JSON.parse(data.toString()), res);
    }
  });
}
function getTemplate(titles, res) {
  fs.readFile('./template.html', (err, data) => {
    if (err) {
      hadError(err, res);
    } else {
      formatHtml(titles, data.toString(), res);
    }
  });
}
function formatHtml(titles, tmpl, res) {
  const html = tmpl.replace('%', titles.join('</li><li>'));
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(html);
}
function hadError(err, res) {
  console.error(err);
  res.end('Server Error');
}
继续优化上述代码,出错尽早返回:
const http = require('http');
const fs = require('fs');

http.createServer((req, res) => {
  getTitles(res);
}).listen(8000, '127.0.0.1');

function getTitles(res) {
  fs.readFile('./titles.json', (err, data) => {
    if (err) return hadError(err, res);
    getTemplate(JSON.parse(data.toString()), res);
  });
}

function getTemplate(titles, res) {
  fs.readFile('./template.html', (err, data) => {
    if (err) return hadError(err, res);
    formatHtml(titles, data.toString(), res);
  });
}

function formatHtml(titles, tmpl, res) {
  const html = tmpl.replace('%', titles.join('</li><li>'));
  res.writeHead(200, { 'Content-Type': 'text/html'});
  res.end(html);
}

function hadError(err, res) {
  console.error(err);
  res.end('Server Error');
}

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|分享学习  

GMT+8, 2024-5-2 21:34 , Processed in 0.046355 second(s), 5 queries , File On.

声明:本站严禁任何人以任何形式发表违法言论!

本站内容由网友原创或转载,如果侵犯了您的合法权益,请及时联系处理!© 2017 zamxqun@163.com

皖公网安备 34010402700634号

皖ICP备17017002号-1

快速回复 返回顶部 返回列表