封装读取文件(node js)

时间:2023-03-10 02:31:57
封装读取文件(node js)

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

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

              封装读取文件(node js)

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

 var http=require('http');
var fs=require('fs');
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html/css;charset=utf-8'});
var url=req.url;
var fileName="";
switch(url){
case '/':
fileName='index.html';
read(fileName,res)
break;
case '/list.html':
fileName='list.html';
read(fileName,res)
break;
case '/student.html':
fileName='student.html'
read(fileName,res);
break;
case '/style.css':
fileName='style.css';
read(fileName,res);
break;
default :
res.write('请输入正确的路径');
res.end();
}
}).listen(3000,function(){
console.log('服务器已启动!!!')
})
function read(fileName,res){
fs.readFile(fileName,'utf-8',function(err,data){
if(err){
var msg=fileName+'文件读取失败'
res.end(msg);
}else{
res.end(data)
}
})
}

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

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

       封装读取文件(node js)这是执行index.html的效果

        封装读取文件(node js)这是执行list.html路径的效果图

        封装读取文件(node js)这是执行style.css的效果图

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

            封装读取文件(node js)我们可以设置默认情况下输出,给我们提醒

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

            封装读取文件(node js)

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