nodejs 笔记一

实现一个自动抓取Nodejs api 文档,用于本地查阅

目录结构:

一:抓取官网api列表

地址:http://nodeapi.ucdok.com/api/_toc.json

 1 //获取目录
 2 var http= require('http')
 3 var bufferhelper= require('./bufferhelper.js')
 4 var fs= require('fs') 
 5 //获取目录
 6 http.get('http://nodeapi.ucdok.com/api/_toc.json',function(req){  
 7     var _b = new bufferhelper()
 8     req.on('data',function(d){ 
 9         _b.concat(d)
10     }) 
11     req.on('end',function(){
12         getList(_b.toBuffer().toString('utf8'))
13     })
14 }).on('error',function(e){
15     console.log('error:'+e.message)
16 })
17 
18 function getList(file){
19     var _sj=[];
20     var _j=JSON.parse(file);
21     _j.desc.forEach(function(item){
22         if(item.type=='text'){
23             _sj.push(item.text)
24         }
25     })
26     fs.writeFile('json/list.json', JSON.stringify(_sj), function (err) {
27         if (err) throw err 
28         console.log('load ok')
29     })
30 } 
抓api列表

 二:通过列表拿到具体的条目

 1 //通过目录下载子目录
 2 var http= require('http')
 3 var bufferhelper= require('./bufferhelper.js')
 4 var fs= require('fs') 
 5 
 6 fs.readFile('json/list.json',function(err,data){
 7     if(err) throw err;
 8     var _j=JSON.parse(data);
 9     _j.forEach(function(item){ 
10         var _url=item.match(/([^]]*)/g); 
11         var _s=_url[_url.length-1];
12         _s=_s.substr(1,_s.length-6); 
13         getUrl(_s);
14     })
15 })
16 function getUrl(url){
17     http.get('http://nodeapi.ucdok.com/api/'+url+'json',function(req){  
18         var _b = new bufferhelper()
19         req.on('data',function(d){ 
20             _b.concat(d)
21         }) 
22         req.on('end',function(){
23             getList(_b.toBuffer().toString('utf8'),url)
24         })
25     }).on('error',function(e){
26         console.log('error:'+e.message)
27     })
28 
29 }
30 
31 function getList(file,url){ 
32     fs.writeFile('json/list/'+url+'json', file, function (err) {
33         if (err) throw err 
34         console.log('load '+url+'json ok')
35     })
36 } 
子目录json

三:建个本地站点来展示拿到的数据。

1:写个web服务,简单实现,主要是能请求文件和请求方法。从网上找了两个文件,bufferhelper.js buffer辅助类,mine.js 处理请求文件格式

 1 var http = require('http');
 2 var url=require('url');
 3 var fs=require('fs');
 4 var mine=require('./mine').types;
 5 var config=require('./mine').config;
 6 var path=require('path'); 
 7 
 8 var handle =function(request,response){ 
 9     var pathname = url.parse(request.url).pathname;
10     var realPath = path.join("./", pathname); 
11     console.log('realPath:'+realPath);
12     var ext = path.extname(realPath); 
13     ext = ext ? ext.slice(1) : 'unknown'; 
14     console.log('ext:'+ext);
15     
16     if(ext=='unknown'){
17         //realPath上一级为文件,最后为请求的方法名 
18         var control=path.dirname(realPath); 
19         var cpath=path.join("./",control+'.js'); 
20         fs.exists(cpath,function(exists){
21             if (!exists) {
22                 response.writeHead(404, {
23                     'Content-Type': 'text/plain'
24                 }); 
25                 response.write("This request URL " + cpath + " was not found on this server.");
26                 response.end();
27             }else{
28                 var action=require('./'+control)[path.basename(realPath)];
29                 try{
30                     action(request,response);
31                 }catch(err){
32                     var errMsg= 'Error:'+ new Date().toISOString() +''+ request.url + err.stack || err.message || 'unknow error';
33                     response.write(errMsg);
34                     response.end();    
35                 }  
36             }
37         }); 
38     }
39     else{
40         fs.exists(realPath, function (exists) { 
41             if (!exists) {
42                 response.writeHead(404, {
43                     'Content-Type': 'text/plain'
44                 }); 
45                 response.write("This request URL " + pathname + " was not found on this server.");
46                 response.end();
47             } else {  
48                 fs.readFile(realPath, "binary", function (err, file) {
49                     if (err) {
50                         response.writeHead(500, {
51                             'Content-Type': 'text/plain'
52                         });
53                         response.end(err);
54                     } else {
55                         var contentType = mine[ext] || "text/plain";
56                         response.writeHead(200, {
57                             'Content-Type': contentType +';charset=utf-8'
58                         }); 
59                         response.write(file, "binary");
60                         response.end();
61                     }
62                 });
63             }
64         });
65     }
66 }
67 
68 var server =http.createServer(); 
69 server.on('request',function(req,res){
70     try{
71         handle(req,res);
72     }catch(err){
73         var errMsg= 'Error:'+ new Date().toISOString() +''+ req.url + err.stack || err.message || 'unknow error';
74         console.error(errMsg);
75         res.end(errMsg);
76     }
77 }); 
78 server.listen(8888,'127.0.0.1',function(){
79     console.log('listen: 127.0.0.1:8888');
80 });
View Code

2:webserver-start.cmd 用来启动服务,就一行代码

@echo off
node %cd%webserver.js
pause
View Code

3:然后了,文件就down到本地了,做个简单页面测试下。这里用了下 window.onhashchange事件 

 1 <body>
 2     <div id='main'>
 3         
 4     </div>
 5 </body>
 6 <script>
 7     $(function(){
 8         var h=window.location.hash;
 9         if(h!=''){
10             getjson();
11             return;
12         }
13         getList();
14     });
15     
16     window.onhashchange=function(e){
17         getjson();
18     };
19     
20     function getjson(){
21         var h=window.location.hash;
22         if(h==''){
23             getList();
24             return;
25         }
26         h=h.substr(1);
27         $.get('../json/list/'+h+'.json',function(j){ 
28             $('#main').empty().append(JSON.stringify(j));
29         });
30     }
31     
32     function getList(){
33         $.get('../json/list.json',function(j){
34             var ul=$('<ul></ul>');
35             var list='';
36             j.forEach(function(item){
37                 var _url=item.match(/([^]]*)/g); 
38                 var _s=_url[_url.length-1];
39                 _s=_s.substr(1,_s.length-7); 
40                 list+='<li><a href="#'+_s+'">'+item+'</a></li>';
41             });
42             ul.append(list);
43             $('#main').empty().append(ul);
44         });
45     }
46 </script>

 大概先出个效果

 

作者:zc
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/jmzs/p/4651993.html