zoukankan      html  css  js  c++  java
  • 封装读取文件(node js)

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

      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.当输入错误的路径时,要给予我们提醒的话,我可以这样作:

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

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

                 

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

          

        

  • 相关阅读:
    session 和 aplication 相关总结
    asp.net网站发布时碰到的一些问题
    考前防脑瘫防挂分预防针
    【游记】NOIP2021 白给记
    SELECT list is not in GROUP BY clause and contains nonaggregated
    StringUtils.isEmpty()
    gitLab生成SSH私钥后上传代码及获取代码
    tomcat配置https请求访问
    Mybatis:映射文件概述 & 增删改查
    Mybatis:核心文件概述
  • 原文地址:https://www.cnblogs.com/szkjoker717666/p/12063533.html
Copyright © 2011-2022 走看看