20160809 笔记 nodejs文件和URL操作

复习:编写简单的http服务器

const http = require("http");
const ip = "192.168.25.128";
const port = 3000;

http.createServer((req,res)=>{
res.writeHead(200,{'content-type:':'text/html'});
res.write('hello');
res.end();
}).listen(port,ip,()=>{
console.log('server start');
});

改写程序

url地址访问

const http = require("http");
const url = require("url");
const ip = "192.168.25.128";
const port = 3000;
var f =function(req,res){
var pathname = url.parse(req.url).pathname;
res.write(pathname);
res.end();
}
var f2 = function(){
console.log('server');
}
http.createServer(f).listen(port,ip,f2);

文件操作

touch 创建空文件

获取文件内容
const http = require("http");
const url = require("url");
const fs = require("fs");
const ip = "192.168.25.128";
const port = 3000;

//fs.readFile('a.txt',(err,data)=>{
    // if(err)throw err;
    // console.log(data.toString());
// });
var data = fs.readFileSync('a.txt');//读取文件内容
var f =function(req,res){
    var pathname = url.parse(req.url).pathname;
res.write(pathname);
    res.write(data.toString());
res.end();
}
var f2 = function(){
  console.log('server');
}
http.createServer(f).listen(port,ip,f2);

根据请求判断访问的模板

const http = require("http");
const url = require("url");
const fs = require("fs");
const ip = "192.168.25.128";
const port = 3000;
var server = new http.Server();
server.listen(port,ip);
server.on('req',function(req,res) {
    var pathname = url.parse(req.url).pathname;
    // var userurl = url.parse(pathname);

    switch (pathname) {
        case '' || '/':
            fs.readFile('./index.html',function(err,content) {
                if (err) {
                    console.log(err);
                }else {
                    res.writeHead(200, {'Content-Type':'text/html:charset=utf-8'});
                    res.write(content);
                    res.end();
                }
            });
            break;
        default:

    }
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,010评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,663评论 25 708
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,974评论 6 342
  • 如今步入大三,在学生会里当了一个小小的部长。最近则思考一个问题,在大学中究竟是么是能力。大学四年认识不少人,做...
    睿思涵说阅读 532评论 0 2
  • 很多人感叹买的起车,但消费不起。今年油价将迎来5连跌,车主们能省下一些油钱。在选择保险的时候,要合理的购买车险,也...
    c2b6ac647ea0阅读 368评论 0 1