|
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');
}
|
|