Discuss
/
JavaScript
/
用同步的方法处理web服务都会阻塞应用,要用连续的异步回调
用同步的方法处理web服务都会阻塞应用,要用连续的异步回调
Topic source递归版本异步回调,支持配置白名单列表
var fs = require('fs'),
url = require('url'),
path = require('path'),
http = require('http');
var root = path.resolve('.');
var default_index = ['index.html', 'default.html'];
console.log('root dir: ' + root);
// 递归回调函数
function checkFileEx(t_list,filepath,req,rep) {
// 不在白名单返回404
if (!t_list) {
console.log('404 ' + req.url);
rep.writeHead(404);
rep.end('404 Not Found');
}
var f_name = t_list.pop()
fs.stat(path.join(filepath, f_name), (err2, stat2) => {
if (!err2) {
console.log('200 ' + req.url);
rep.writeHead(200);
fs.createReadStream(path.join(filepath, f_name)).pipe(rep);
} else {
// 开始递归
checkFileEx(t_list,filepath,req,rep)
}
});
}
var server = http.createServer((req, rep) => {
var pathname = url.parse(req.url).pathname;
var filepath = path.join(root, pathname);
console.log('filepath: ' + filepath);
fs.stat(filepath, (err, stat) => {
if (!err && stat.isFile()) {
console.log('200 ' + req.url);
rep.writeHead(200);
fs.createReadStream(filepath).pipe(rep);
} else if (!err && stat.isDirectory()) {
// 复制白名单
var bi_bk = default_index.slice();
// 递归回调
checkFileEx(bi_bk,filepath,req,rep);
} else {
console.log('404 ' + req.url);
rep.writeHead(404);
rep.end('404 Not Found');
}
})
})
server.listen(8888);
- 1
起伏