美文网首页
Node 中的fs模块结合http模块一起使用

Node 中的fs模块结合http模块一起使用

作者: 乔乔_老师 | 来源:发表于2018-07-17 20:26 被阅读0次

使用http调用fs模块

const http=require('http');   //引入http模块
const fs=require('fs');    //引入fs模块
var server=http.createServer(function(req,res){//创建一个服务
    var file_name='./www'+req.url;//把请求的文件放在一个www的文件夹中
      fs.readFile(file_name,function(err,data){
            if(err){
                     res.write('404');
           }else{
                   res.write(data);
           }
         res.end();
      });
})
server.listen(8080);//监听

在命令行中启动 带有上述代码的server.js文件,同时使用localhost:8080/index.html

如果有index.html就会显示html中的东西,如果没有就会报404

相关文章

网友评论

      本文标题:Node 中的fs模块结合http模块一起使用

      本文链接:https://www.haomeiwen.com/subject/qowgpftx.html