码迷,mamicode.com
首页 > Web开发 > 详细

封装读取文件(node js)

时间:2019-12-18 21:35:27      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:color   code   来讲   col   lis   显示   img   提醒   执行   

      我们都会简单的读取文件,今天我们就来讲一下用函数封装读取文件。

 

  1.首先我们要先建好文件

              技术图片

    2.我们在index.js里面写入代码:

 1 var http=require(‘http‘);
 2 var fs=require(‘fs‘);
 3 http.createServer(function(req,res){
 4     res.writeHead(200,{‘Content-Type‘:‘text/html/css;charset=utf-8‘});
 5     var url=req.url;
 6     var fileName="";
 7     switch(url){
 8         case ‘/‘:
 9         fileName=‘index.html‘;
10         read(fileName,res)
11         break;
12         case ‘/list.html‘:
13         fileName=‘list.html‘;
14         read(fileName,res)
15         break;
16         case ‘/student.html‘:
17         fileName=‘student.html‘
18         read(fileName,res);
19         break;
20         case ‘/style.css‘:
21         fileName=‘style.css‘;
22         read(fileName,res);
23         break;
24         default :
25         res.write(‘请输入正确的路径‘);
26         res.end();
27     }
28 }).listen(3000,function(){
29     console.log(‘服务器已启动!!!‘)
30 })
31 function read(fileName,res){
32     fs.readFile(fileName,‘utf-8‘,function(err,data){
33         if(err){
34             var msg=fileName+‘文件读取失败‘
35             res.end(msg);
36         }else{
37             res.end(data)
38         }
39     })
40 }

 

     3.打开cmd命令窗口,输入node  idnx.js

     4.输入地址后,我们看一下效果

       技术图片这是执行index.html的效果

 

 

 

 

 

         技术图片这是执行list.html路径的效果图

 

 

 

         技术图片这是执行style.css的效果图

 

         5.当输入错误的路径时,要给予我们提醒的话,我可以这样作:

            技术图片我们可以设置默认情况下输出,给我们提醒

 

           在浏览器中显示出来就是这样:

             技术图片

 

         好了,以上就是我们今天的全部内容了,希望对大家有所帮助!!!

      

    

封装读取文件(node js)

标签:color   code   来讲   col   lis   显示   img   提醒   执行   

原文地址:https://www.cnblogs.com/szkjoker717666/p/12063533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!